在php中使用exit(0)的方法声明退出状态(成功退出还是由于某情况意外终止),这样做有什么好处?这与直接退出有什么区别
ringa_lee
ringa_lee 2017-04-11 09:52:15
[PHP讨论组]

就像
下面的代码

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

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

有什么区别?

虚心向各位大神请教一二

ringa_lee
ringa_lee

ringa_lee

全部回复(1)
PHPz

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

讲道理还是拿文档说事:

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表示没有错误).

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号