Home >Backend Development >PHP Tutorial >What are the benefits of using the exit(0) method in PHP to declare the exit status (successful exit or unexpected termination due to certain circumstances)? What is the difference between this and exiting directly?

What are the benefits of using the exit(0) method in PHP to declare the exit status (successful exit or unexpected termination due to certain circumstances)? What is the difference between this and exiting directly?

WBOY
WBOYOriginal
2016-08-18 09:16:161318browse

Like
the code below

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

and

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

What’s the difference?

Humbly ask the masters for advice

Reply content:

Like
the code below

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

and

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

What’s the difference?

Humbly ask the masters for advice

Let me give the conclusion first: There are subtle differences.

Be reasonable or rely on documents:

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.

To put it simply: if it is a string, it will be printed. If it is a number, it will be used as the exit status code and will not be printed.

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

Execute the above two lines of code respectively, and it is obvious that the results are the same.

The difference is:
Comment the second line and execute the following command in the terminal:
php test.php // Print "error"
echo $? //Print 3

Comment the first line and execute the following command in the terminal:
php test.php // Print "error"
echo $? //Print 0

In other words, when the parameter of eixt() is of type int, it will be used as the exit status code.
$?Explanation: Stores the exit value of the last command that was executed (the exit status of the last command, 0 means no error).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn