Home > Article > Backend Development > Example of using the register_shutdown_function function to intercept fatal errors in PHP, fatalerror_PHP tutorial
When we are working on projects, fatal errors occasionally occur due to carelessness. If display_errors is set to off, the user will see a blank page. If it is set to on, the fatal error message will be displayed (of course, normal people will not do this).
So is there any way we can intercept fatal errors in advance and feedback them to users in our own custom friendly form? There is a function in PHP called register_shutdown_function that allows us to set another function that can be called when the execution is shut down. That is to say, when our script execution is completed or unexpectedly dies and the PHP execution is about to shut down, this function will is called.
Please see an example below:
Copy code The code is as follows:
$flag = false;
function deal_error(){
global $flag;
If (!$flag){
)
}
Return false;
}
register_shutdown_function("deal_error");
//Will fail with fatal error
//$obj = new NotExistClass(); //Introducing undefined classes
require('./test.php');
$flag = true;
At the program entry, we set the flag to false, and finally set it to true, indicating that the program is executing normally. If the flag is not true at the end, it means it died somewhere in the middle. At this time, register_shutdown_function will be called to output our customized error result.