PHP Object Life Time

梦想与她 提交于 2020-01-13 02:15:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3982051/php-object-life-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!