The WeakMap class
The WeakMap class
A is map (or dictionary) that accepts objects as keys. However, unlike the
otherwise similar , an object in a key of
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 , the object will be garbage collected and removed
from the . 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``SplObjectStorage``WeakMap``WeakMap``WeakMap
implements ,
(via ),
and , so in most cases it can be used in the same fashion as an associative array.
WeakMap``ArrayAccess``Traversable``IteratorAggregate``Countable
WeakMap``ArrayAccess``Countable``IteratorAggregate
Voorbeeld: usage example
<?php
$wm = new WeakMap();
$o = new stdClass;
class A {
public function __destruct() {
echo "Dead!\n";
}
}
$wm[$o] = new A;
var_dump(count($wm));
echo "Unsetting...\n";
unset($o);
echo "Done\n";
var_dump(count($wm));
int(1)
Unsetting...
Dead!
Done
int(0)