先思考一个问题:
如下代码会向页面显示什么?
代码如下 | |
| |
代码如下 | |
die(123); ?> |
die(123);
?>
曾经有段时间我一直认为 页面会显示 123,但实践结果告诉我,答案错了,页面一片空白!
代码如下 | |
echo '123'; die(); ?> |
代码如下 | |
echo '123'; <🎜> die(); <🎜> ?> |
A piece of information on the Internet:
The difference between exit() and die() in PHP
PHP manual: die()Equivalent to exit().
Note: die() and exit() are both functions to terminate script execution; in fact, the two names exit and die point to the same function, and die() is an alias of the exit() function. This function only accepts one parameter, which can be a value returned by a program or a string, or no parameters can be entered, and the result is no return value.
Reference: Although the two are the same, there are subtle selectivity in their usual use. For example:
When the value passed to the exit and die functions is 0, it means that the execution of the script is terminated early, usually with the name exit().
The code is as follows | |||||
echo "1111";
exit(0);
echo "2222"; |
// 22222 will not be output because when the program reaches exit(0), the script has been terminated early and "will die immediately".
代码如下 | |
$fp=fopen("./readme.txt","r") or die("不能打开该文件"); |
2 // In this case, if the fopen function is called and returns a Boolean value of false, die() will immediately terminate the script and print
immediately3 // The string passed to it, "I can say one or two words before I die".
------------------------------------------------ ----------------------------------
Returning to the previous topic, why doesn’t the following code output 123 to the page?
The code is as follows | |
| |
代码如下 | |
die(123); // 或 exit(123); ?> |
die(123);
// or exit(123);
?>
Summary by yourself:
1. Functionally, die() is equivalent to exit();
2. PHP has multiple running modes, either in website form or in script form (no Web server is required).
When PHP is run in script form, it is recommended to use exit():
For example, the Bash Shell script language, when it wants to stop running, will use the exit() function to terminate the script and allow the output content to the running environment (usually stored in a global variable), but the output content is only Can be a number, indicating the "end status of the command".
In other words, exit(123) only outputs a running status of 123, rather than actually outputting 123 to the console. If you want to output 123 to the console, the code must be changed to the following form:
The code is as follows | |
| |
代码如下 | |
exit('123'); |
exit('123');
?>
When PHP is running as a website, it is recommended to use die():
But at this time, die (number) is meaningless, because it will not output a number string to the page. In other words, if you want the page to terminate and output numbers, you have to change it to the following form
代码如下 | |
die('123'); ?> |
The code is as follows | |
die('123'); <🎜> ?> |