Custom Error Handlers

While assert() is a good function to make extensive use of, it only catches errors you were expecting. While that might sound obvious, it is quite crucial—if an error you have not planned for occurs, how are you to find out about it? Never fear—there are two functions available to make your life much easier: set_error_handler() and error_log().

The set_error_handler() function takes the name of a user callback function as its only parameter, and it notifies PHP that any errors should use that function to handle them. The user function needs to accept a minimum of two parameters, but in practice you will likely want to accept four. These are, in order, the error number that occurred, the string version of the error, the file the error occurred in, and the line of the error. For example:

    function on_error($num, $str, $file, $line) {
            print "Encountered error $num in $file, line $line: $str\n";
    }

    set_error_handler("on_error");
    print $foo;

On line four, we define the general error handler to be the on_error() function, then call print $foo, which, as $foo does not exist, is an error and will result in on_error() being called. The definition of on_error() is as described: it takes four parameters, then prints them out to the screen in a nicely formatted manner.

There is a second parameter to set_error_handler() that lets you choose what errors should trigger the error handler, and it works like the error_reporting directive in php.ini. However, you can only have one ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.