Wednesday, April 11, 2018

Can a PHP script execute common code before exit() | register_shutdown_function | PHP execute a piece of code before process terminated by exit() or die() method

Registers a callback to be executed after script execution finishes or exit() is called.
Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
<?php 
namespace App\Test;

class CallbackClass { 
    function CallbackFunction() { 
        // refers to $this 
    } 

    function StaticFunction() { 
        // doesn't refer to $this 
    } 
} 

function NonClassFunction() { 
} 
?> 

there appear to be 3 ways to set a callback function in PHP (using register_shutdown_function() as an example): 

1: register_shutdown_function('NonClassFunction'); 

2: register_shutdown_function(array('\App\Test\CallbackClass', 'StaticFunction')); 

3: $o =& new CallbackClass(); 
   register_shutdown_function(array($o, 'CallbackFunction')); 

1 comment: