wiki/content/20201110103654-php_weap_maps.md

786 B

id title
954a4b48-f3a5-4ef6-a2ea-93f843250c68 PHP Weap Maps

Description

Weak maps1 allow creating a map from objects to arbitrary values (similar to SplObjectStorage) without preventing the objects that are used as keys from being garbage collected. If an object key is garbage collected, it will simply be removed from the map. This will save a lot of headaches for people writing things like ORMs.

Syntax

class Foo
{
    private WeakMap $cache;

    public function getSomethingWithCaching(object $obj): object
    {
        return $this->cache[$obj]
           ??= $this->computeSomethingExpensive($obj);
    }
}

Related

Footnotes