tags:

views:

19

answers:

2

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  A: 

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.

Emil Vikström
Why do you say the object will not be destroyed if you save it to session?
Alin Purcaru
It will be destroyed, removed from memory and even the destructor may be run, but you can restore it afterwards (on the next page). Maybe I shouldn't have mentioned it at all because it doesn't seem related to the question.
Emil Vikström
A: 

Hello,

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.

Alin Purcaru