What does register_shutdown_function
do?
I have no understanding whatsoever on the usage of it and what it does. I know you can use it and fit nicely with a custom error handler, but I don't know what to pass through it, what to do with it, etc.
Could someone explain it in the easiest terms for this coding newbie?
This is actually a pretty simple function. So you have a php script:
<?php
echo "Here is my little script";
function endScript(){
echo "My little Script has finished";
}
register_shutdown_function('endScript');
?>
Basically what happens is your script runs and when it's finished because we added this line register_shutdown_function('endScript');
it will call the function endScript and finally output My little script has finished
.
Here's a little extra from the documentation:
Registers a callback to be executed after script execution finishes or exit() is called.Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
*Update
A great use for it is when you frequently use the function called exit()
in php.
For example:
<?php
function endScript(){
echo "My little Script has finished";
}
register_shutdown_function('endScript');
$result = some_intricate_function()
if($result == 0){
exit();
}
$result = some_other_intricate_function()
if($result == 0){
exit();
}
/* and this keeps reoccurring */
?>
Now notice that even though you call exit multiple times you don't have to call the endScript
function before exit each time. You registered it in the begining and now you know that if you ever exit or your script finishes then your function is called.
Now of course my shutdown function is pretty useless; but it can become useful if you need to clean things (ie. Close open file handles, save some persistent data, etc)
register_shutdown_function
registers a shutdown hook, which is a function to be executed when the script shuts down. It takes a callback function as parameter, which is the function to be executed.
I recommend that you check out the function's documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With