Home >Backend Development >PHP Tutorial >Detailed explanation of PHP register_shutdown_function function_PHP tutorial
Scripts often die, and they don't always look good. We don't want to show the user a fatal error, or a blank page (when display_errors is set to off).
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, causing the PHP execution to be shut down, our function will be called. Therefore, we can use the method of setting a variable to false at the beginning of the script, and then setting it to true at the end of the script to let PHP close the callback function to check whether the script is completed.
If our variable is still false, we know that the last line of the script was not executed, so it must have died somewhere along the way. I've prepared a very basic example that demonstrates when a fatal error needs to be displayed, How should you give the user some appropriate feedback. You can make the example look better by turning off the display of fatal errors (Annotation: you can set display_errors and error_reporting).
$clean = false; function shutdown_func(){ global $clean; if (!$clean){ die("not a clean shutdown"); } return false; } register_shutdown_function("shutdown_func"); $a = 1; $a = new FooClass(); // Will fail with fatal error $clean = true; ?>
As you can see, if the clean variable is not set to true when the shutdown callback function is running, the shutdown_func function will print something. This thing can be packaged into a class (without using global variables).
PHP provides the register_shutdown_function() function, which can call back the registered function before the script terminates, that is, the function that is executed when the PHP program is executed.
php programmer station
Example:
Note: register_shutdown_function means calling the function after all PHP statements are executed. Do not understand it as calling the function when the client closes the streaming browser page.
The calling condition can be understood like this:
1. When the page is forced to stop by the user
2. When the program code times out
3. When the PHP code execution is completed
Excerpted from Smile Every Day