Weak maps 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.

In PHP 7.4 first-class support for weak references was already introduced. However, raw weak references are only of limited usefulness by themselves and weak maps are much more commonly used in practice. It is not possible to implement an efficient weak map on top of PHP weak references, because the ability to register a destruction callback is not provided.

The general use case for weak maps is to associate data with individual object instances, without forcing them to stay alive and thus effectively leak memory in long-running processes. For example, a weak map may be used to memoize a computation result:

class FooBar { private WeakMap $cache ; public function getSomethingWithCaching ( object $obj ) { return $this -> cache [ $obj ] ?? = $this -> computeSomethingExpensive ( $obj ) ; } // ... }