PHP 对象生命周期
我正在使用 PHP 5.2。如果我在一页上new一个对象,这个对象什么时候会被销毁?当用户转到另一个 .php 页面时,对象是否会自动销毁,或者我需要显式调用 __destructor ?
I am using PHP 5.2. If I new an object at one page, when will this object be destructed? Is the object destructed automatic at the time that user go to another .php page or I need to call __destructor explicitly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它将在页面加载结束时被破坏(从内存中卸载),或者如果您之前取消设置对它的所有引用。您不必手动销毁它,因为 PHP 总是在脚本末尾清理所有内存。
事实上,您永远不应该自己调用 __destruct。当您想要销毁对象时,使用 unset 取消设置对对象的引用。事实上,__destruct 不会销毁您的对象,它只是 PHP 在销毁之前自动调用的函数,这样您就有机会在销毁之前进行清理。您可以根据需要调用 __destruct 多次,而无需恢复记忆。
但是,如果您已将对象保存到会话变量中,它将“休眠”而不是被销毁。请参阅 __sleep 的手册。当然,它仍然会从内存中卸载(并保存到磁盘),因为 PHP 在脚本之间的内存中不保存任何内容。
It will be destructed (unloaded from memory) at the end of the page load, or if you unset all references to it earlier. You will not have to destroy it manually since PHP always cleans up all memory at the end of the script.
In fact, you should never call __destruct yourself. Use unset to unset the reference to an object when you want to destroy it. __destruct will in fact not destroy your object, it's just a function that will get called automatically by PHP just before the destruction so you get a chance to clean up before it's destroyed. You can call __destruct how many times as you want without getting your memory back.
If, however, you've saved the object to a session variable, it will "sleep" rather than be destroyed. See the manual for __sleep. It will still be unloaded from memory (and saved to disk) of course since PHP doesn't hold anything in memory between scripts.
当当前脚本中不再有对所有对象的引用时,所有对象都会被销毁(调用 __destruct 方法)。当您
取消设置
包含该对象的所有变量或脚本结束时,就会发生这种情况。All objects are destructed (the
__destruct
method is called) when there is no more reference to them in the current script. This happens when you eitherunset
all the variables that contained that object or when the script ends.