Last Updated: February 25, 2016
·
450
· dboskovic

Avoid Recursive References in PHP

If you're ever wondering why some class instances are not being garbage collected, make sure you're not initiating a child class with a reference to the parent. If you are, make sure to destroy the reference to the child class when you no longer need it.

class A {
    function __construct () {
        $this->b = new B($this);
    }
    function __cleanup() {
        $this->b = null;
    }
}

class B {
    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}
// this will create a massive memory bloat
for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
}

// this will keep the memory clean
for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
    $a->__cleanup();
}

https://bugs.php.net/bug.php?id=33595 (don't be fooled by the closed status, this bug is still alive and kicking in 5.5.14)