The register_shutdown_function Function
The register_shutdown_function
function allows registering a callback function that will be executed when the script terminates or on a fatal error. The first parameter is the function name or an anonymous function, subsequent parameters (optional) are arguments for this function.
Syntax
register_shutdown_function(callable $callback, mixed ...$args): void
Example
Simple function registration on termination:
<?php
function shutdown() {
echo 'Script finished';
}
register_shutdown_function('shutdown');
echo 'Script running...';
?>
Execution result:
Script running...Script finished
Example
Using an anonymous function:
<?php
register_shutdown_function(function() {
echo 'Cleanup completed';
});
echo 'Main operations...';
?>
Execution result:
Main operations...Cleanup completed
Example
Passing arguments to the shutdown function:
<?php
function logShutdown($message) {
echo $message;
}
register_shutdown_function('logShutdown', 'Script shutdown at: ' . date('H:i:s'));
echo 'Processing data...';
?>
Execution result:
Processing data...Script shutdown at: [current_time]
See Also
-
the
error_reporting
function,
which sets the error reporting level -
the
set_exception_handler
function,
which sets the exception handler