CKTIS / PHP
WeakMap
Map object identities to data without a strong reference from the map to its keys.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
new WeakMap()Map object identities to data without a strong reference from the map to its keys. When a key loses its final strong reference, its entry disappears. Values are held strongly; a value that refers back to its key can keep that key alive. Use for per-object derived data. In PHP 8.4 cycle collection can release an isolated value-to-key cycle. When the key is its own value, count is still 1 after unset and becomes 0 after gc_collect_cycles().
$m=new WeakMap(); $obj=new stdClass(); $m[$obj]="cached"; $alias=$obj; unset($obj);
$while=count($m); unset($alias); echo json_encode([$while,count($m)]);
$key=new stdClass(); $m[$key]=$key; unset($key); $before=count($m); gc_collect_cycles(); echo PHP_EOL,json_encode([$before,count($m)]);
[1,0]
[1,0]
Examples
<?php
$m=new WeakMap(); $obj=new stdClass(); $m[$obj]="cached"; $alias=$obj; unset($obj);
$while=count($m); unset($alias); echo json_encode([$while,count($m)]);
$key=new stdClass(); $m[$key]=$key; unset($key); $before=count($m); gc_collect_cycles(); echo PHP_EOL,json_encode([$before,count($m)]);
Result
[1,0] [1,0]