What are the differences between die()
and exit()
functions in PHP
?
I think both have the same functionality, but I doubt there is something different in both... what is it?
What are the differences between die()
and exit()
functions in PHP
?
I think both have the same functionality, but I doubt there is something different in both... what is it?
PHP manual on die:
You can even do
die;
the same way asexit;
- with or without parens.The only advantage of choosing
die()
overexit()
, might be the time you spare on typing an extra letter ;-)They sound about the same, however, the exit() also allows you to set the exit code of your PHP script.
Usually you don't really need this, but when writing console PHP scripts, you might want to check with for example Bash if the script completed everything in the right way.
Then you can use exit() and catch that later on. Die() however doesn't support that.
Die() always exists with code 0. So essentially a die() command does the following:
Which is the same as:
This page says
die
is an alies ofexit
, so they are identical. But also explains that:So, call me paranoid, but there may be no
die
ing in the future.This output from https://3v4l.org demonstrates that die and exit are functionally identical.
When using command line,
Will print to "Error" to STDOUT and exit with error code 0.
if you want to exit with error code 1, you have to:
It could be useful while executing php scripts from command line or shell scripts and you want to see if the script terminated with a non zero exit code. copied answer of charanjeet from Quora
Functionally, they are identical. So to choose which one to use is totally a personal preference. Semantically in English, they are different. Die sounds negative. When I have a function which returns JSON data to the client and terminate the program, it can be awful if I call this function jsonDie(), and it is more appropriate to call it jsonExit(). For that reason, I always use exit instead of die.