Search code examples
phpgarbage-collectionspl

PHP5: SplObjectStorage garbage collection


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:

  • having the managed object's destructor inform the storage to remove references to it; this is not acceptable as these objects should not be aware of the manager;
  • parsing debug_zval_dump() to get the reference count; not acceptable as well, IMHO too "hacky" for a serious application.

Any other ideas?


Solution

  • 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