@ 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)
WeakMap 是将对象作为 key 来访问的 map(或者说字典)。然而,与其它类似 SplObjectStorage 不同,WeakMap 中的对象 key 不影响对象的引用计数。也就是说,如果在任何时候对其唯一的剩余引用是 WeakMap key,那么该对象将会被垃圾收集并从 WeakMap 移除。它的主要用法是从对象中编译数据派生缓存,这种场景下不需要存活得比对象更久。
WeakMap 实现了 ArrayAccess、 Iterator、Countable, 因此大多数情况下,它能和关联数组一样使用。
示例 #1 Weakmap 用法示例
<?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)
@ 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