array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'class.weakmap.php', 1 => 'WeakMap', ), 'up' => array ( 0 => 'reserved.interfaces.php', 1 => '预定义接口和类', ), 'prev' => array ( 0 => 'weakreference.get.php', 1 => 'WeakReference::get', ), 'next' => array ( 0 => 'weakmap.count.php', 1 => 'WeakMap::count', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'language/predefined/weakmap.xml', ), 'extra_header_links' => array ( 'rel' => 'alternate', 'href' => '/manual/en/feeds/class.weakmap.atom', 'type' => 'application/atom+xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 8)
WeakMap 是将对象作为 key 来访问的 map(或者说字典)。然而,与其它类似 SplObjectStorage 不同,WeakMap 中的对象 key 不影响对象的引用计数。也就是说,如果在任何时候对其唯一的剩余引用是 WeakMap key,那么该对象将会被垃圾收集并从 WeakMap 移除。它的主要用法是从对象中编译数据派生缓存,这种场景下不需要存活得比对象更久。
WeakMap 实现了 ArrayAccess、 Traversable(通过 IteratorAggregate)和 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)