Home > Article > Backend Development > The difference between die and exit in php
Think about a question first:
What will the following code display to the page?
1 |
<?php |
2 | die (123); |
3 | ?> |
There was a time when I always thought that the page would display 123, but the practical results told me that the answer was wrong and the page was blank!
I still don’t know why, but 123 is not output. In order to let the page output 123, I modified it to the following code:
1 |
<?php |
2 | echo '123' ; |
3 | die (); |
4 | ?> | PHP Manual
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 to terminate the execution of the script early, usually using the name exit().1
echo
"1111"
;
| 2
exit |
| 3
echo |
// 22222 will not be output, because when the program runs to exit(0), the script has been terminated early and "will die immediately".
| When the program errors, you can pass it a string, which will be output as it is on the system terminal, usually using the name die().
|
=
fopen
(
, "r " | )
or die ( "Cannot open the file" );
2
// If the fopen function is called When returning the Boolean value false, die() will immediately terminate the script and immediately print the string passed to it, "You can say something before you die" Two sentences". |
Back to the previous topic, why doesn’t the following code output 123 to the page?
|
|
|
|
(123);
| 3
|
| 4
?> |
1. Functionally, die() is equivalent to exit();
| 2. PHP has multiple running methods, either in website form or script form (no web server is required).
When PHP is running as a script, it is recommended to use exit(): |
|
|
2
exit
(
'123'
);
|
|
?>
<ul><li>When PHP is running as a website, it is recommended to use die(): </li></ul>
<p>But at this time <span>die (number)</span> is meaningless because it will not output to the page
Numeric string, that is to say, if you want the page to terminate and output numbers, you have to change it to the following form</p>
<p></p>
<table><tbody><tr>
<td><code>1 |
<?php |
2 | die ( '123' ); |
3 | ?> |
The above introduces the difference between die and exit in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.