Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(PHP) Unset an object from within the class code

Tags:

oop

php

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,

like image 859
bruno.braga Avatar asked Feb 21 '23 19:02

bruno.braga


2 Answers

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.

like image 87
Frankie Avatar answered Mar 01 '23 22:03

Frankie


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);
like image 22
Finbarr Avatar answered Mar 02 '23 00:03

Finbarr