This is my first time posting to stackoverflow, but I these threads have helped me tremendously!
Anywho, onto my question... are there any instances when the destructor in PHP is NOT called? The reason I ask is because I have a mapper class which maps data to objects and in the constructor, I start a transaction and in the destructor I'll call a commit (I'll also have a member function which can also do the committal, if necessary). If there are any instances when the destructor isn't called, I'd like to know so I can anticipate it happening and plan appropriately.
Thanks very much!
According to the manual, destructors are executed even if the script gets terminated using die()
or exit()
:
The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this SO question, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).
The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)
The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different
It does not get executed on parse errors (because the whole script won't be interpreted)
The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.
All in all, it looks pretty reliable.
The downside of doing things other than cleanup in the destructor, though, is that your options there are somewhat limited. You can't throw exceptions any more (except if you catch them again inside the destructor), you can't output any error messages, you can't really rely on the presence of other objects (like the database interface) any more ..... I don't have deep experience in working with destructors but I'm not sure whether what you're planning to do is a feasible idea.
I would just like to add, if you have a fatal error inside a destructor, it can stop other destructors from executing.