Is the __destruct method necessary for PHP?
The manual said that
The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in an开发者_开发问答y order in shutdown sequence.
Doesn't the PHP GC enough? Could someone give an example that __destruct
method is necessary?
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.
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: Can I trust PHP __destruct() method to be called?
The __destruct
magic method is necessary for PHP in the sense that if you want the power to explicitly, automatically, and consistently lower the reference count for injected objects (say, a database wrapper object, etc...), that happen to be shared with other objects, then the __destruct
magic method is a reliable and predictable place to do this. Sure, it is more of a convention than an absolute requirement, but why reinvent the wheel (C++, Java, etc ...)? PHP is not just for webpages, so we should keep that in mind.
精彩评论