首页 > 解决方案 > 在 PHP 中,我调用 exit(1)。如何在 PHP 中获取状态码?

问题描述

在 PHP 中,我有一个 Class name CustomClass,然后我调用exit(1). 在析构函数上CustomClass,我如何获得退出的状态码?我应该得到 的参数exit(1),即1

class CustomClass
{
    public function __destruct()
    {
        //how to get the status code of exit() ?
        echo "exit code is? \n";
    }
}

try {
    $customObj = new CustomClass();

    throw New Exception('some error....');
} catch (Throwable $e) {
    echo "error: " . $e->getMessage() . "\n";
    exit(1);
}

echo "This echo will not output\n";

我希望得到 的参数exit(1),即1

标签: php

解决方案


由于它的工作(如评论中所写),我将在这里给出一个答案,以便更好地查看:

如果你像 exit(int) 那样使用 PHP exit(),它不会打印任何东西,但是如果你传递一个字符串,它将被打印:

status 如果 status 是一个字符串,这个函数在退出之前打印状态。

如果 status 是一个整数,则该值将用作退出状态而不打印。退出状态应在 0 到 254 的范围内,退出状态 255 由 PHP 保留,不得使用。状态 0 用于成功终止程序。 https://www.php.net/manual/en/function.exit.php

因此,在退出时打印 int 的解决方案是使用一个函数:

function execute($statusCode) { 
    echo $statusCode; 
} 
exit(execute(3)); // Will exit and print 3

BR


推荐阅读