PHP 8.3.0 RC 6 available for testing

WeakMap 类

(PHP 8)

简介

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

WeakMap 实现了 ArrayAccessIteratorCountable, 因此大多数情况下,它能和关联数组一样使用。

类摘要

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
10
mrblc at example dot com
7 months ago
@ 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.
up
-13
malferov at gmail dot com
8 months ago
<?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
To Top