PHP exit() Function
The PHP exit() function outputs a message and terminates execution of the current script.
Shutdown functions and object destructors will always be executed even if exit is called.
exit 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 die().
Syntax
exit(status)
Parameters
status |
Optional. Specify status as int or string.
|
Return Value
No value is returned.
Example: exit() example
The example below shows how to use exit() function.
<?php error_reporting(E_ERROR); $filename = 'test.txt'; $file = fopen($filename, 'r') or exit("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 exit; exit(); exit(0); //exit with an error code exit(1); exit(0376); //octal ?>
Example: shutdown functions and destructors run regardless
The example below shows that the shutdown functions and object destructors are executed even if exit 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 exit exit(); echo 'This will not be displayed.'; ?>
The output of the above code will be:
Shutdown: shutdown() Destruct: Foo::__destruct()
❮ PHP Miscellaneous Reference