[FIXED] The PHP unset doesn't clear the reference completely

Issue

I have a simple class and assign its instance to its static variable. When I unset the instance, not sure why it doesn’t actual release the memory.

class Foo {
    public static $app;

    public function __construct() {
        self::$app = $this;
    }
}

$foo = new Foo;

unset($foo);

var_dump($foo);

var_dump(Foo::$app);

Result:

Warning: Undefined variable $foo in /var/www/index.php on line 16
NULL object(Foo)#1 (0) { }

Obviously, the static $app point to the itself instance, we have unset the instance but doesn’t really clean the memory for this variable. Why did it happen? Are the instance of the $app and the $foo different ones?

Solution

You’ve only unset a reference to an object of class Foo, and that object will get garbage-collected next time garbage collector runs.

Classes, once loaded, live in the memory until request is terminated, and so will their static properties. If they hold a pointer to an object, that object won’t be garbage-collected. If you want to garbage-collect Foo::$app, you’ll need to unset it too.

Answered By – jedrzej.kurylo

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published