Oliver Nassar

PHP's register_shutdown_function function

July 29, 2011

In making a very low-footprint, clean MVC framework (7 core files, ~22kb in size), I stumbled upon the function register_shutdown_function. And I'm really impressed by it.

I'm not sure why it took me this long to find it, but it's purpose is really simple: when a script is finished (either by no more code being found in the compiled source or a call to the exit function is made), it executes this function. You can register it as a method of a class or a standalone function. You can also pass in parameters to use, but in short, this function gets called when everything else has finished.

Here's how I use it within my framework:

/**
 * shutdown function. Handles buffer-flushing and error-handling.
 * 
 * @access public
 * @return void
 */
function shutdown()
{
    $error = error_get_last();
    if (empty($error)) {
        $response = Request::getResponse();
        if ($response) {

            // response measuring
            header('Response: ' . round(microtime(true) - $GLOBALS['rst'], 4));

            // echo response
            echo $response;
        }
        exit(0);
    } else {
        require_once APP . '/includes/error.inc.php';
    }
}

// buffer-flushing and error/exception handling
register_shutdown_function('shutdown');

I check whether an error/exception has occurred. If it hasn't, I grab the response generated by the framework, set a header to determine how long it took to generate that response, and spit it out.

If an error has occurred, I simply spit out my standard error template. Worth noting is that if a call is made to the exit function from within the shutdown method/function, it does not recursively process itself. Rather, it ends the script immediately.

What I like so much about it is it's simplicity. When everything else is done, it kicks into action. It's clean, and gives you a lot of control over what gets flushed to the buffer.