Today we will discuss one magical function named "register_shutdown_function".
function allows you to execute a block of code whenever your script ends for any reason.
Whether your page exit()s or die()s or just finishes, a developer has a hook to run whatever code he/she deems necessary. And not just one function either… you can use this call to register as many shutdown functions as you want, and they will get executed in the order that they get applied. But of course, you must be careful: PHP will happily give you more rope than you will ever need to hang yourself. A lot of people may consider the use of this function to be magic, and you’ll want to be very clear that what you’re doing is documented.
Use of this function is very straight-forward.
I just tested with Apache, PHP being used as Apache module. I created an endless loop like this:
class X
{
function __destruct()
{
$fp = fopen("/var/www/dtor.txt", "w+");
fputs($fp, "Destroyed\n");
fclose($fp);
}
};
$obj = new X();
while (true) {
// do nothing
}
Here's what I found out:-
- pressing STOP button in Firefox does not stop this script
- If I shut down Apache, destructor does not get called
- It stops when it reaches PHP max_execution_time and destuctor does not get called
However, doing this:
function shutdown_func() {
$fp = fopen("/var/www/htdocs/dtor.txt", "w+");
fputs($fp, "Destroyed2\n");
fclose($fp);
}
register_shutdown_function("shutdown_func");
while (true) {
// do nothing
}
shutdown_func gets called. So this means that class destuctor is not that good as shutdown functions. :-)
Enjoy !! :-)
ReplyDeleteCan you help me with this?