PHP的__destruct方法是必需的吗? [英] Is the __destruct method necessary for PHP?
问题描述
一旦所有对
特定对象的引用都被移除,析构函数方法就会被调用或者当对象显式地
被销毁或者在关闭顺序中以任何顺序时。
PHP PHP不够用吗?有人能举出一个例子,说明 __ destruct
方法是必要的吗?
虽然GC可以管理本地资源(例如其他对象和对象图)外部资源(如文件句柄)仍必须手动处理。例如,设想一个MyFile类,其中析构函数将确保该文件(如果打开的话)将被关闭 - 虽然可以说它是更好的使它成为对对象调用Close / Dispose操作的要求,但析构函数可以是在这种情况下用作回退机制。
我会反对GC语言中的析构函数的一般用法。他们可以引入很多细微的问题,比如明显的非确定性和意外保持对象活跃的能力 - 即使在使用引用计数的PHP等语言中也是如此。 (Java / JVM和.NET模型使用的终结器更加挑剔。)
快乐编码。
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 any 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.
这篇关于PHP的__destruct方法是必需的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!