首頁  >  文章  >  後端開發  >  在php中使用exit(0)的方法宣告退出狀態(成功退出還是因為某情況意外終止),這樣做有什麼好處?這與直接退出有什麼區別

在php中使用exit(0)的方法宣告退出狀態(成功退出還是因為某情況意外終止),這樣做有什麼好處?這與直接退出有什麼區別

WBOY
WBOY原創
2016-08-18 09:16:161256瀏覽

就像
下面的程式碼

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

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

有什麼區別?

虛心向各位大神請教一二

回覆內容:

就像
下面的程式碼

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

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

有什麼區別?

虛心向各位大神請教一二

先給結論: 有細微差別。

講道理還是拿文檔說事:

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 and shall not be 0. to terminate the program successfully.
Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

簡單點說就是: 如果是字串,就會印出來,如果是數字,就會作為退出的狀態碼,不會被印出來。

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

分別執行上面兩行程式碼,很明顯可以看出結果是一樣的。

差別在於:
註解第二行,在終端執行下方指令:
php test.php // 列印"出錯"
echo $? //列印 3

註解第一行,在終端執行下方指令:
php test.php // 列印"出錯"
echo $? //列印 0

也就是說,eixt()當參數為int型別的時候,會作為退出狀態碼。
$?解釋:Stores the exit value of the last command that was executed(最後一條指令的退出狀態,0表示沒有錯誤).

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn