register_shutdown_function after all the other register_shutdown_functions

By admin - Last updated: Friday, March 14, 2008 - Save & Share - Leave a Comment

PHP’s register_shutdown_function lets me run code after it finishes running the script, be that naturally or forcibly. This makes it a perfect fit for a whole bunch of things, like running maintenance database queries or showing debugging information.

function do_maintenance()
{
  $db->doSomeQueries();
}
 
function debug_write()
{
  echo 'some debugging information';
}
 
// Last things to execute
register_shutdown_function( 'do_maintenance' );
register_shutdown_function( 'debug_write' );

There’s one caveat, and it’s explained in the PHP documentation:

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered.

This means that if I also want to see debug output from the queries in the do_maintenance function, I have to make sure that debug_write is always the last registered function.

This can be inconvenient. Luckily, PHP has a function that allows a script to run code after it’s finished all of it’s processing… And it lets me register another shutdown function inside that function.

register_shutdown_function(
  create_function( '', 'register_shutdown_function(\'debug_write\');' ) // Really last thing to execute
); 
 
register_shutdown_function( 'do_maintenance' ); // Last thing to execute

This assures that the function that it registered will always be the last one, and this way, despite having the debug function registered before the maintenance function, the debug function will still execute last.

Posted in PHP • Tags: Top Of Page

Write a comment

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page. Click here for instructions on how to enable JavaScript in your browser.