drawkcaB | Backward Compatible logo

rants and tips about software

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.

Milan Babuškov, 2008-10-25
Copyright © Milan Babu┼íkov 2006-2024