PHP die() Function
The PHP die() function outputs a message and terminates execution of the current script.
Shutdown functions and object destructors will always be executed even if die is called.
die is a language construct and it can be called without parentheses if no status is passed.
Note: Please note that, this is a language construct and not a function. This language construct is equivalent to exit().
Syntax
die(status)
Parameters
status |
Optional. Specify status as int or string.
|
Return Value
No value is returned.
Example: die() example
The example below shows how to use die() function.
<?php error_reporting(E_ERROR); $filename = 'test.txt'; $file = fopen($filename, 'r') or die("Unable to open file $filename"); ?>
The output of the above code will be:
Unable to open file test.txt
Example: exit status example
In the example below status is passed as an int which is used as the exit status by the program.
<?php //exit program normally die; die(); die(0); //exit with an error code die(1); die(0376); //octal ?>
Example: shutdown functions and destructors run regardless
The example below shows that the shutdown functions and object destructors are executed even if die is called.
<?php //defining a class class Foo { public function __destruct() { echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL; } } //defining a shutdown function function shutdown() { echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL; } //creating an object of class Foo $foo = new Foo(); //registering the shutdown function register_shutdown_function('shutdown'); //calling die die(); echo 'This will not be displayed.'; ?>
The output of the above code will be:
Shutdown: shutdown() Destruct: Foo::__destruct()
❮ PHP Miscellaneous Reference