Can I trust PHP __destruct() method to be called?

Viewed 35195

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

6 Answers

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.

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.

It's worth noting, that although destructors are likely to be called, there is no guarantee they will be called, as this tale from The Daily WTF illustrates:

“All right,” I sighed. As tempting as it was to ask him to describe the just-made-up concept of process marshaling, I decided to concede. And just at that moment, I thought of the perfect rebuttal. “But what if you just, say, pull the plug? A Finally block __destruct won’t execute when the computer is turned off!”

I expected the developers to jump back and chastise me for an “unreasonable scenario.” But instead, their faces turned bright white. They slowly turned to look at each other. It was clear that they made the same mistake that many before them had made: believing Try-Finally to be as infallible as things like database transactions.

“And… umm…” I said slowly, breaking the awkward silence, “that’s why… you should… never put critical… business transaction code in finally blocks.”

It's okay to assume that destructor will be called if you're just freeing resources or doing some logging, but they aren't safe to use for 'undo-ing' previous operations to try to make some code ACID compliant.

Related