I'm learning PHP from w3school's PHP Tutorial.
In a chapter "PHP Error Handling", I am studying about Creating Custom Error Handler.
I came across following program in which a Custom Error Handler Function is defined. See the below code.
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
The output of above code is as below :
Error: [8] Undefined variable: test
My doubt is as I have not specified the error level and error message anywhere in the program then from where and how the custom error function is getting error level and error message?
How this whole custom error handling mechanism works in PHP?
Please explain me in simple and lucid language. You can explain with the help of some other example too. In fact it would be better for me to understand as well.
The error level your custom handler receives is one of PHP's E_* constants. You find the list of possible constants and their values here.
In your example the use of the undefined variable
$test
would normally cause a PHP Notice. Therefore you get the value 8 (which isE_NOTICE
) as$errno
in your custom handler. You cannot change the error message, as this error is generated internally by PHP.Try it: remove the custom error handler and look at the error PHP gives you for using the undefinded variable. This is exactly the level and message your custom handler gets called with.
I suggest you try out your handler using the
trigger_error()
function (see here). This is the only way to set error level and message yourself.Note also that it doesn't matter what is set in error_reporting ini setting! Your custom handler always receives ALL error messages regardless of the level.
Please read through the manual pages linked above.