WeakMap 类

(PHP 8)

简介

WeakMap 是将对象作为 key 来访问的 map(或者说字典)。然而,与其它类似 SplObjectStorage 不同,WeakMap 中的对象 key 不影响对象的引用计数。也就是说,如果在任何时候对其唯一的剩余引用是 WeakMap key,那么该对象将会被垃圾收集并从 WeakMap 移除。它的主要用法是从对象中编译数据派生缓存,这种场景下不需要存活得比对象更久。

WeakMap 实现了 ArrayAccessTraversable(通过 IteratorAggregate)和 Countable, 因此大多数情况下,它能和关联数组一样使用。

类摘要

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* 方法 */
public count(): int
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): void
}

示例

示例 #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)

目录

add a note

User Contributed Notes 2 notes

up
7
Samu
7 months ago
PHP's implementation of WeakMap allows for iterating over the contents of the weak map, hence it's important to understand why it is sometimes dangerous and requires careful thought.

If the objects of the WeakMap are "managed" by other services such as Doctrine's EntityManager, it is never safe to assume that if the object still exists in the weak map, it is still managed by Doctrine and therefore safe to consume.

Doctrine might have already thrown that entity away but some unrelated piece of code might still hold a reference to it, hence it still existing in the map as well.

If you are placing managed objects into the WeakMap and later iterating over the WeakMap (e.g. after Doctrine flush), then for each such object you must verify that it is still valid in the context of the source of the object.

For example assigning a detached Doctrine entity to another entity's property would result in errors about non-persisted / non-managed entities being found in the hierarchy.
up
0
Anton
3 months ago
Keep in mind that if Enum case is put as a key to WeakMap, it will never be removed because it will always have unless 1 reference to it under the hood (not sure why, probably because enum is basically a constant).
Therefore, both WeakMaps below will always have key Enum::Case. However, you still are able to unset it manually:

$weakMap = new WeakMap();
$object = Enum::Case;

$weakMap[$object] = 123;
unset($object);
var_dump($weakMap->count()); // 1

///

$weakMap = new WeakMap();
$weakMap[Enum::Case] = 123;
var_dump($weakMap->count()); // 1

///

$weakMap = new WeakMap();
$weakMap[Enum::Case] = 123;
unset($weakMap[Enum::Case]);
var_dump($weakMap->count()); // 0
To Top