@ malferov at gmail dot com
It works as intended. As soon as:
<?php
$wp[new stdClass()] = 'value';
?>
is executed, number of references is zero and garbage collector will remove it.
(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.
Exemplo #1 Weakmap 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));
O exemplo acima produzirá:
int(1) Unsetting... Dead! Done int(0)
@ malferov at gmail dot com
It works as intended. As soon as:
<?php
$wp[new stdClass()] = 'value';
?>
is executed, number of references is zero and garbage collector will remove it.
<?php
$wp = new WeakMap();
// It's not working.
// Has no error but not adding dynamically specifying object to map;
// garbage collector will not be able to clear unnamed value, as I suppose
$wp[new stdClass()] = 'value';
echo $wp->count() . PHP_EOL; // 0
// It's working, as expected
$obj = new stdClass();
$wp[$obj] = 'value';
echo $wp->count(); // 1