I'm using a SplObjectStorage to keep information about managed objects. When my objects get destructed, I would like the SplObjectStorage
to automatically cleanup the objects which have no external references anymore.
I can see only two options for this right now:
Any other ideas?
Time has gone by & php has evolved, if you are here & are using php 8.2, there is another option.
You can use a WeakMap instead of the SplObjectStorage
A WeakMap
is similar to the splObjectStorage
in the sense that they both use objects as keys.
A WeakMap, however, does not prevent objects that fall out of scope everywhere else from being garbage collected
For context, here is an splObjectStorage
example:
$store = new splObjectStorage();
$object = new stdClass();
$store[$object] = 'This is my object';
var_dump($store->count()); // int(1)
unset($object);
var_dump($store->count()); // int(1)
Note that the $store
still has the object even if the object was unsset
...and, here is a WeakMap
example:
$store = new WeakMap();
$object = new stdClass();
$store[$object] = 'This is my object';
var_dump($store->count()); // int(1)
unset($object);
var_dump($store->count()); // int(0)
Note that after unsset
'ing the $object
, $store
count is 0