views:

2492

answers:

3

In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?

+5  A: 

The destructor will be called when the all references are freed, or when the script terminates. I assume this means when the script terminates properly. I would say that critical exceptions would not guarantee the destructor to be called.

The PHP documentation is a little bit thin, but it does say that Exceptions in the destructor will cause issues.

Geoff
+6  A: 

It's also worth mentioning that, in the case of a subclass that has its own destructor, the parent destructor is not called automatically.

You have to explicitly call parent::__destruct() from the subclass __destruct() method if the parent class does any required cleanup.

Mark Biek
I believe this is true only when the child class implements its own __destruct(), otherwise the parent __destruct() will be called.
Geoff
Very true. I edited to clarify.
Mark Biek
+4  A: 

There is a current bug with circular references that stops the destruct method being called implicitly. http://bugs.php.net/bug.php?id=33595 It should be fixed in 5.3

MOdMac