In PHP when any fatal error happen, (ex. Fatal error: Call to undefined function phpinf() .. or .. Class ‘User’ not found etc ..) it stops executing script, as a result a broken page is shown. This is very unexpected behavior to users. So we need to handle this and show an user friendly error message to the browser.
To handle the fatal error and some other errors we can use a method register_shutdown_function which accepts a function name as a param that will be called when current script execution completed. So in case of any fatal error happen, the script execution will end and call the registered method instantly. and thus we can takeover the execution flow and do our custom task, ex. report admin about the error, show user an appropriate error message etc. By the way, this registered method will be called each time current script ends its execution. So in that method we need to check the last error if there is any real error happen. There are many PHP Error Constants.
Here is a simple example
/*
* define the shutdown method, which will be called each time this script execution ends
*/
function shutdown()
{
// get last error
$lastError = error_get_last();
// show user error message if any error happen
if(!is_null(criticalError)){
// get error type
$errorType = $lastError['type'];
$criticalError = array(E_ERROR , E_PARSE , E_CORE_ERROR, E_COMPILE_ERROR ,E_RECOVERABLE_ERROR);
if(in_array($errorType, $criticalError )){
// mail to admin
// mail('admin@example.com', ....);
}
// print a proper message to output
echo "Sorry, an unexpected error happen, please check later";
}
}
// register the shutdown function
register_shutdown_function('shutdown');
// now do some fatal error like call a class which does not exsits
User::load(); // here User Class is not included
Here is the output ..
Sorry, an unexpected error happen, please check later
The more you do mistake, the more you get the chance to learn
Cheer$