PHP Velho Oeste 2024

The WeakMap class

(PHP 8)


A WeakMap is map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar SplObjectStorage, an object in a key of WeakMap does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a WeakMap, the object will be garbage collected and removed from the WeakMap. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object.

WeakMap implements ArrayAccess, Iterator, and Countable, so in most cases it can be used in the same fashion as an associative array.

Class synopsis

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* Methods */
public count(): int
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): void


Example #1 Weakmap usage example

= new WeakMap();

$o = new stdClass;

A {
public function
__destruct() {

$wm[$o] = new A;


The above example will output:


Table of Contents

add a note add a note

User Contributed Notes 1 note

4 months ago
PHP's implementation of WeakMap allows for iterating over the contents of the weak map, hence it's important to understand why it is sometimes dangerous and requires careful thought.

If the objects of the WeakMap are "managed" by other services such as Doctrine's EntityManager, it is never safe to assume that if the object still exists in the weak map, it is still managed by Doctrine and therefore safe to consume.

Doctrine might have already thrown that entity away but some unrelated piece of code might still hold a reference to it, hence it still existing in the map as well.

If you are placing managed objects into the WeakMap and later iterating over the WeakMap (e.g. after Doctrine flush), then for each such object you must verify that it is still valid in the context of the source of the object.

For example assigning a detached Doctrine entity to another entity's property would result in errors about non-persisted / non-managed entities being found in the hierarchy.
To Top