Question

I was looking for the __destroy() method in ArrayObject but found no implementation. If I set the variable containing an ArrayObject to NULL, will it correctly destroy all the objects stored in it and free memory? Or should I iterate the ArrayObject to destroy each of the objects before unsetting it?

Était-ce utile?

La solution

When you unset or null the ArrayObject only the ArrayObject instance is destroyed. If the ArrayObject contains other objects, those will only be destroyed as long as there is no reference to them from somewhere else, e.g.

$foo = new StdClass;
$ao = new ArrayObject;
$ao[] = $foo;
$ao[] = new StdClass;
$ao = null;     // will destroy the ArrayObject and the second stdClass
var_dump($foo); // but not the stdClass assigned to $foo

Also see http://www.php.net/manual/en/features.gc.refcounting-basics.php

Autres conseils

In PHP you never really have to worry about memory usage beyond your own scope. unset($obj) will work fine, in your case. Alternatively you could simply leave the function you're in:

function f() {
    $obj = new ArrayObject();

    // do something
}

And the data will be cleaned up just fine.

PHPs internal memory management is rather simply: a reference count is kept for each piece of data and if that's 0 then it gets released. If only the ArrayObject holds the object, then it has a refcount of 1. Once the ArrayObject is gone, the refcount is 0 and the object will be gone.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top