PHP对象生存时间 [英] PHP Object Life Time

查看:95
本文介绍了PHP对象生存时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP 5.2.如果我在一页上新建一个对象,该对象什么时候会被破坏?当用户转到另一个.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?

推荐答案

在页面加载结束时,或者如果您更早取消了对其的所有引用,它将被销毁(从内存中卸载).您不必手动销毁它,因为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.

实际上,您应该从不调用__destruct自己.要销毁对象时,请使用取消设置取消对对象的引用. __destruct实际上不会破坏对象,它只是一个在破坏之前由PHP自动调用的函数,因此您有机会在破坏之前进行清理.您可以根据需要调用__destruct多少次,而无需恢复内存.

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.

但是,如果将对象保存到会话变量中,它将休眠"而不是被销毁.请参见 __sleep 的手册.当然,由于PHP在脚本之间没有在内存中保存任何内容,因此仍将其从内存中卸载(并保存到磁盘).

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.

这篇关于PHP对象生存时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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