The first part of this article demonstrated basic errorhandling in PHP, explaining the various error types and illustrating theprocess of building a custom error handler. But that's just the tip ofthe iceberg - this concluding part goes a step further, showing you totrigger your own errors, and log error messages to a file, database oremail address.
PHP also comes with a restore_error_handler() function, which allows you to restore the previous error handler. This is useful if you need to switch between handlers in a single script. Consider the following simple example, which demonstrates:
<?php
// custom error handler
function eh($type, $msg, $file, $line, $context)
{
echo "This is the custom error handler speaking";
}
// trigger a warning
// this will be caught by the default handler
// since nothing else has been defined
trigger_error("Something bad happened", E_USER_WARNING);
// define a new handler
set_error_handler("eh");
// trigger another warning
// this will be caught by the custom handler trigger_error("Something
bad happened", E_USER_WARNING);
// rollback to default handler
restore_error_handler();
// trigger another warning
// this will be caught by the default handler trigger_error("Something
bad happened", E_USER_WARNING);
?>
Here's what the output looks like:
Warning: Something bad happened in /usr/local/apache/htdocs/x2.php on
line 12 This is the custom error handler speaking
Warning: Something bad happened in /usr/local/apache/htdocs/x2.php on
line 26