In this article, you will learn how to set a user-defined error handler function in PHP.
The set_error_handler() function in PHP allows to set a user-defined error handler function. The standard PHP error handler is overridden if this function is used, and the user-defined error handler must stop the script, die() if required.
what is the syntax of the SET_ERROR_HANDLER() function in php?
set_error_handler(errorhandler, E_ALL | E_STRICT)
Parameter | Description |
---|---|
errorhandler | Required. Specifies the name of the function to be run at errors |
E_ALL|E_STRICT | Optional. Specifies on which error report level the user-defined error will be shown. Default is “E_ALL” |
examples of the SET_ERROR_HANDLER() function
Example 1. In this example, we set a user-defined error handler function with the set_error_handler() function, and trigger an error (with trigger_error()).
<?php
// A user-defined error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Custom error:</b> [$errno] $errstr<br>";
echo " Error on line $errline in $errfile<br>";
}
// Set user-defined error handler function
set_error_handler("myErrorHandler");
$test=2;
// Trigger error
if ($test>1) {
trigger_error("A custom error has been triggered");
}
?>