PHP的__destruct方法是必需的吗? [英] Is the __destruct method necessary for PHP?

查看:160
本文介绍了PHP的__destruct方法是必需的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

手册说:


一旦所有对
特定对象的引用都被移除,析构函数方法就会被调用或者当对象显式地
被销毁或者在关闭顺序中以任何顺序时。

PHP PHP不够用吗?有人能举出一个例子,说明 __ destruct 方法是必要的吗?

析构函数与释放内存没有直接关系 - 相反,它是一个钩子,允许在对象符合回收条件时运行自定义代码。也就是说,它与构造函数相反 - 构造函数不分配内存(如在调用构造函数之前由GC完成的那样),因此析构函数不释放内存(如这将由GC完成)。

虽然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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆