PHP 对象生命周期

发布于 2024-09-28 05:14:21 字数 101 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独自唱情﹋歌 2024-10-05 05:14:21

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

挽手叙旧 2024-10-05 05:14:21

当当前脚本中不再有对所有对象的引用时,所有对象都会被销毁(调用 __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 either unset all the variables that contained that object or when the script ends.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文