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

phpregister_shutdown_function(callable $callback, mixed ...$args): void

Example

Simple function registration on termination:

php<?php
  function shutdown() {
    echo 'Script finished';
  }
  
  register_shutdown_function('shutdown');
  echo 'Script running...';
?>

Execution result:

phpScript running...Script finished

Example

Using an anonymous function:

php<?php
  register_shutdown_function(function() {
    echo 'Cleanup completed';
  });
  
  echo 'Main operations...';
?>

Execution result:

phpMain operations...Cleanup completed

Example

Passing arguments to the shutdown function:

php<?php
  function logShutdown($message) {
    echo $message;
  }
  
  register_shutdown_function('logShutdown', 'Script shutdown at: ' . date('H:i:s'));
  echo 'Processing data...';
?>

Execution result:

phpProcessing data...Script shutdown at: [current_time]

See Also