What are the differences in die() and exit() in PH

2019-01-02 19:08发布

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 exit die
17条回答
看淡一切
2楼-- · 2019-01-02 19:43

PHP manual on die:

die — Equivalent to exit

You can even do die; the same way as exit; - with or without parens.

The only advantage of choosing die() over exit(), might be the time you spare on typing an extra letter ;-)

查看更多
只靠听说
3楼-- · 2019-01-02 19:45

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:

<?php
echo "I am going to die";
exit(0);
?>

Which is the same as:

<?php
die("I am going to die");
?>
查看更多
看风景的人
4楼-- · 2019-01-02 19:46

This page says die is an alies of exit, so they are identical. But also explains that:

there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script.

So, call me paranoid, but there may be no dieing in the future.

查看更多
刘海飞了
5楼-- · 2019-01-02 19:47

This output from https://3v4l.org demonstrates that die and exit are functionally identical. enter image description here

查看更多
十年一品温如言
6楼-- · 2019-01-02 19:49

When using command line,

 die("Error");

Will print to "Error" to STDOUT and exit with error code 0.

if you want to exit with error code 1, you have to:

  fwrite(STDERR, "Error");
    exit(1);

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

查看更多
泪湿衣
7楼-- · 2019-01-02 19:49

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.

查看更多
登录 后发表回答