This article mainly introduces examples of using the register_shutdown_function function to intercept fatal errors in PHP. Friends who need it can refer to it
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).
Then is there any way for us to 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 the code. The code is as follows:
$flag = false;
Function deal_error(){
global $flag;
if (!$flag){
die("This is a rough question, please try again later");
}
return false;
}
register_shutdown_function("deal_error");
// Will fail due to fatal error
//$obj = new NotExistClass(); //Introducing undefined classes
require('./test.php');
$flag = true;
We set the flag to false at the program entry, 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.
If the above class is not defined, non-existent files are introduced (require or require_once must be used), etc., it will lead to fatal errors. Of course, if your program is missing a punctuation mark or has an extra special character or something, then there is nothing you can do.