Is it possible to unset (clean or un-instantiate) an object of a class by executing code of that particular class?
My scenario is one that, for some reason, I reach a point that the object has no meaning to exist anymore, so I want to make sure that is will not be used again by killing its reference in memory.
Here is a snippet example:
class Foo {
public $bar = "doh!";
function destroy() {
// ???
}
}
$o = new Foo();
echo $o->bar . '\n';
$o->destroy();
echo $o->bar . '\n'; // I expect an error here...
If I do a "unset" command outside the class code, it works, obviously:
$o = new Foo();
unset($o);
echo $o->bar . '\n'; // PHP Notice: Undefined property: Foo::$bar in ...
But I tried to do it inside the "destroy" method, by calling "unset", or creating a custom "__destruct", but none worked.
Any ideas are very welcome.
Cheers,
Take into account that you can't explicitly destroy an object.
The ways to allow PHP Garbage Collector to act upon an object are:
$var = null; // set to null
unset($var); // unset
The object will stay there. However, if you unset the object and your script pushes PHP to the memory limits, the objects not needed will be garbage collected. I would go with unset() as it seams to have better performance (not tested but documented on one of the comments from the PHP official manual).
That said do keep in mind that PHP always destroys the objects as soon as the page is served. So this should only be needed on really long loops and/or heavy intensive pages.
What's wrong with unset($o)
? You could wrap that behaviour up in a static class method if it really offends you:
class Foo {
public static function destroy(&$foo) {
unset($foo);
}
}
Foo::destroy($o);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With