Software Woes

Rants, tips and tricks



Sunday, October 26, 2008



PHP destructor vs shutdown function

I found an interesting problem. In some of my PHP classes I needed to ensure that destructor is called, even if user aborts the execution. Well, I learned that user cannot actually abort it since clicking the Stop button in your browser does not stop PHP, it keeps going until either the script finishes (destructor gets called) or PHP timeout is reached (destructor is not called).

I got worried about this second case. After some time investigating, reading comments in PHP online manual (that's why it's better to use online than offline manual for PHP) I got to the following solution:


public function __construct($canvasWidth, $canvasHeight, $tickness)
{
...
register_shutdown_function(array(&$this, "shutdown"));
}

public function shutdown()
{
...do the stuff you would do in destructor
}


The only problem with this could be if your object gets destroyed before script is complete. So, make sure you either implement some safeguard code, or ensure object's lifetime is 'till the end of script.

2 Comments:

At 7:59 PM, Blogger Callum said...

Re: "The only problem with this could be if your object gets destroyed before script is complete."

What about if you call the method __destruct()instead of shutdown(), and in your constructor do:

register_shutdown_function(array(&$this, "__destruct"));


I'm not sure if that would solve the problem...

 
At 8:05 PM, Blogger Callum said...

Re: "The only problem with this could be if your object gets destroyed before script is complete."

What about if you call the method __destruct()instead of shutdown(), and in your constructor do
register_shutdown_function(array(&$this, "__destruct"));


I'm not sure if that would work...

 

Post a Comment

Links to this post:

Create a Link

<< Home