首页 > 在php中使用exit(0)的方法声明退出状态(成功退出还是由于某情况意外终止),这样做有什么好处?这与直接退出有什么区别

在php中使用exit(0)的方法声明退出状态(成功退出还是由于某情况意外终止),这样做有什么好处?这与直接退出有什么区别

就像
下面的代码

echo '配置错误';
exit(3);  //状态3表示由于配置错误而退出

// 直接退出
exit('配置错误');

有什么区别?

虚心向各位大神请教一二


先给出结论: 有细微区别。

讲道理还是拿文档说事:

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

简单点说就是: 如果是字符串,就会打印出来,如果是数字,就会作为退出的状态码,不会被打印。

<?php
 echo "出错"; exit(3);
 // exit("出错");
?>

分别执行上面两行代码,很显然可以看出结果是一样的。

区别在于:
注释第二行,在终端执行下面命令:
php test.php // 打印"出错"
echo $? //打印 3

注释第一行,在终端执行下面命令:
php test.php // 打印"出错"
echo $? //打印 0

也就是说,eixt()当参数为int类型的时候,会作为退出状态码。
$?解释:Stores the exit value of the last command that was executed(最后一条命令的退出状态,0表示没有错误).

【热门文章】
【热门文章】