exit
(PHP 4, PHP 5, PHP 7, PHP 8)
Terminate the current script with a status code or message
Description
Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit() is called. However, Finally blocks are never executed.
An exit code of 0 is used to indicate that the program succeeded in its tasks. Any other value indicates some sort of error occurred during execution.
exit() is a special function, because it has a dedicated token in the parser, as such it can be used like a statement (i.e. without parentheses) to terminate the script with the default status code.
It is not possible to disable, or create a namespaced function shadowing the global exit() function.
Parameters
statusIf
statusis a string, this function prints thestatusjust before exiting. The exit code returned by PHP is0.If
statusis anint, the exit code returned by PHP will bestatus.NoteExit codes should be in the range
0to254, the exit code255is reserved by PHP and should not be used.WarningPrior to PHP 8.4.0,
exit()did not follow PHP's standard type juggling semantics, nor respect thestrict_typesdeclare.Any value not of type
intwas cast tostringincludingresourceandarrayvalues. As of PHP 8.4.0, it follows the usual type juggling semantics and throws aTypeErroron invalid values.
Return Values
As this terminates the PHP script, no value is returned.
Changelog
| Version | Description |
|---|---|
| 8.4.0 | exit() is now a proper function, therefore it follows the usual type juggling semantics is affected by the strict_types declare, can be called with named arguments, and be a variable functions. |
| 8.4.0 | A parameterless exit() called within shutdown functions or object destructors now resets the exit code to 0; previously the exit code set by an earlier exit() call was kept. |
Examples
Basic exit() example
<?php
// exit program normally
exit();
exit(0);
// exit with an error code
exit(1);
?>exit() example with a string
<?php
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");
?>Shutdown functions and destructors run regardless
<?php
class Foo
{
public function __destruct()
{
echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
}
}
function shutdown()
{
echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}
$foo = new Foo();
register_shutdown_function('shutdown');
exit();
echo 'This will not be output.';
?>The above example will output:
Shutdown: shutdown()
Destruct: Foo::__destruct()exit() as a statement
<?php
// exit program normally with exit code 0
exit;
?>Notes
Prior to PHP 8.4.0, exit() was a language construct and not a function, therefore it was not possible to call it using variable functions, or named arguments.