• PHP Video Tutorials

PHP - register_shutdown_function()



The register_shutdown_function() function can register a function for execution on shutdown.

Syntax

void register_shutdown_function( callable $callback [, mixed $parameter [, mixed $... ]] )

The register_shutdown_function() function can register a function named by function to be executed when script processing is complete. Multiple calls to a register_shutdown_function() can be made, and each can be called in the same order as registered. If we call exit() function within one registered shutdown function, the processing can stop completely, and no other registered shutdown functions can be called.

The register_shutdown_function() function doesn't return any value. If the passed callback is not callable, an "E_WARNING" level error can be generated.

Example 1

<?php
   function say_goodbye() {
      echo "Goodbye!\n";
   }

   register_shutdown_function("say_goodbye");
   echo "Hello!\n";
?>

Output

Hello!
Goodbye!

Example 2

<?php
   function say_goodbye() {
      if(connection_status() == CONNECTION_TIMEOUT) {
         print "Script timeout!\n";
      } else {
         print "Goodbye!\n";
      }
   }

   register_shutdown_function("say_goodbye");
   set_time_limit(1);
   print "Sleeping...\n";
   sleep(1);
   print "Done!\n";
?>

Output

Sleeping...
Done!
Goodbye!

Example 3

<?php 
   class TestDemo { 
      public function __construct() { 
         register_shutdown_function([$this, "f"], "hello"); 
      } 
 
      public function f($str) { 
         echo "class TestDemo->f():" . $str; 
      } 
   } 
 
   $demo = new TestDemo(); 
   echo "before" . PHP_EOL; 
?>

Output

before
class TestDemo->f():hello
php_function_reference.htm
Advertisements