Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

register_shutdown_function()

Synopsis

    void register_shutdown_function ( function callback
    [, mixed param [, mixed ...]] )

The register_shutdown_function() function allows you to register with PHP a function to be run when script execution ends. Take a look at this example:

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

    register_shutdown_function("say_goodbye");
    echo "Hello!\n";
    That would print out the following:
    Hello!
    Goodbye!

You can call register_shutdown_function() several times passing in different functions, and PHP will call all of the functions in the order you registered them when the script ends. If any of your shutdown functions call exit, the script will terminate without running the rest of the functions.

One very helpful use for shutdown functions is to handle unexpected script termination, such as script timeout, or if you have multiple exit() calls scattered throughout your script and want to ensure that you clean up no matter what. If your script times out, you have just lost control over whatever you were doing, so you either need to back up and undo whatever you have just done, or you need to clean up and terminate cleanly. Either way, shutdown functions are perfect: register a clean-up function near the start of the script and, when script timeout happens, the clean-up function will automatically run.

For example, the following script will print out "Sleeping...Goodbye!":

 function say_goodbye() { print "Goodbye!\n"; } register_shutdown_function("say_goodbye"); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page