WeakMap — Object Keys That Don't Leak Memory
PHP 8.0 introduced WeakMap, a map where the keys are objects but holding a key doesn't prevent that object from being garbage collected. It's the perfect structure for per-object caches that would otherwise cause memory leaks.
$cache = new WeakMap();
class QueryBuilder
{
public function build(): string { /* ... */ return 'SELECT ...'; }
}
$qb = new QueryBuilder();
// Associate computed data with the object
$cache[$qb] = $qb->build();
echo $cache[$qb]; // "SELECT ..."
echo count($cache); // 1
// When the object goes out of scope, the WeakMap entry is automatically removed
unset($qb);
echo count($cache); // 0 — cleaned up automatically, no memory leak
Compare this to a plain SplObjectStorage or a regular array keyed by spl_object_id(): both keep the object alive as long as the cache exists. With WeakMap, the cache is truly a side-channel — it holds data about objects without claiming ownership of them.
// Real-world: memoize expensive per-object computations
class MetadataRegistry
{
private WeakMap $cache;
public function __construct()
{
$this->cache = new WeakMap();
}
public function getMetadata(object $obj): array
{
if (!isset($this->cache[$obj])) {
$this->cache[$obj] = $this->computeExpensiveMetadata($obj);
}
return $this->cache[$obj];
}
}
Significance: Memory Safety
Caches that hold strong references to objects are a common source of memory leaks in long-running PHP processes (queues, servers, CLI commands). WeakMap makes object-keyed caches correct by default — no manual cleanup, no lifecycle management required.