Take the 2-minute tour ×

The manual said that


Doesn't the PHP GC enough? Could someone give an example that __destruct method is necessary?

share|improve this question
@Marek I know what this method is, I try to know the situation that should use it. –  xdazz Aug 30 '11 at 8:01
add comment

2 Answers

up vote 16 down vote accepted

A destructor has nothing directly to do with releasing memory - instead it is a "hook" to allow custom code to be run when the object is eligible for reclamation. That is, it's the opposite of the constructor - the constructor does not allocate the memory (as that is done by the GC prior to the constructor being invoked) and thus the destructor does not release the memory (as that will be done by the GC afterwards).

While the GC can manage native resources (e.g. other objects and object graphs) just fine, external resources such as file handles must still be "manually disposed". For instance, imagine a MyFile class, where the destructor would ensure the file, if open, would be closed - while it is arguably "better" to make it a requirement to invoke a Close/Dispose operation upon the object, the destructor can be used as a fall-back mechanism in this case.

I would argue against the general use of destructors in languages with a GC. There are a number of subtle issues they can introduce such as apparent non-determinism and the ability to accidentally keep objects alive - even in languages like PHP that uses reference-counting. (The Java/JVM and .NET models use finalizers which are even more finicky.)

Happy coding.

share|improve this answer
Thanks very much for your kind answer:) –  xdazz Aug 30 '11 at 8:23
+1 this helped me understand __destruct. –  Sethen Maleno Mar 12 '13 at 22:09
>> external resources such as file handles must still be "manually disposed". << Except that PHP frees all resources at the end of the script, so in most cases even this would not be necessary. –  fab Mar 19 '13 at 22:05
add comment

If you're using exceptions, you should try to follow RAII even with PHP. And you must use destructors for RAII. It was invented for C++ but the same logic works with PHP, too. Be warned that in some cases (e.g. fatal error or when exit() is called) PHP may end up calling the destructors in incorrect order which I consider a bug in PHP engine. For normal code and exceptions, the PHP engine seems to work as if it was C++ program.

See also: PHP __destruct() method

share|improve this answer
add comment

Your Answer


