PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.
That is what I am interested in doing...but I'm not totally clear how thats done. Would a call to unset($obj) do the trick and invoke the destructor?
EDIT | After reading the comments on unset() it would appear this is now the case. I don't really care about memory usage I just need the destruct() invoked explicitly...if the object isn't cleaned from memory until script completion, thats fine.
The __destruct() method is call as you describe it -- when the object is unset(). I assume that you can call __destruct() directly because you can call __construct() (as long as they are declared public). But I have not tested that.
And yes, calling __destruct() does not destroy the object. It is the reverse. When an object is destructed then __destruct() is called.
Not to veer off-topic, but why would one want to manually destroy an object? I can understand why you'd set up the __destruct so you can do something WHEN it's destroyed, but why destroy it manually? I've read that PHP takes care of the objects on its own (Garbage collection, is it called?). Is it perhaps for the same reason that we use the singleton pattern in other situations? As in, that you don't want to have two of the same object?
Just wondering what's the reasoning behind wanting to unset( ) an object.
Generally, you do not need to unset() an object, it's up to your requirement.
__destruct() is automatically called when an object of a class is destroyed.
The_Anomaly wrote:Just wondering what's the reasoning behind wanting to unset( ) an object.
The goal would obviously to reduce the memory use of a request. Normally it is best to just let PHP clean things up. And second guessing an optimized garbage collector can lead to worse results. But with you can reduce memory usage on certain unusual scripts.
An example I have had was a reporting script that created a large tree of objects containing the data, processed the tree, and then created a large tree of objects used to generate the report. It was using a lot of memory, but when I unset the first tree it brought the memory usage down a good amount.