Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Object Life Time

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?

like image 505
Terminal User Avatar asked Oct 20 '10 20:10

Terminal User


2 Answers

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.

like image 63
Emil Vikström Avatar answered Nov 19 '22 22:11

Emil Vikström


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.

like image 25
Alin Purcaru Avatar answered Nov 19 '22 21:11

Alin Purcaru