WeakMap class
(PHP 8)
소개
WeakMap은 객체를 키로 받아들이는 맵(또는 사전)입니다. 그러나 다른 유사한 SplObjectStorage와 달리 WeakMap의 키에 있는 개체는 개체의 참조 횟수에 기여하지 않습니다. 즉, 어떤 시점에서 객체에 대한 유일한 나머지 참조가 WeakMap의 키인 경우 해당 객체는 가비지 수집되어 WeakMap에서 제거됩니다. 주요 사용 사례는 개체보다 오래 살 필요가 없는 개체에서 파생된 데이터 캐시를 구축하는 것입니다.
WeakMap은 ArrayAccess, Iterator 및 Countable을 구현하므로 대부분의 경우 연관 배열과 동일한 방식으로 사용할 수 있습니다.
인터페이스 개요
final class WeakMap implements Countable, ArrayAccess, IteratorAggregate {
/* Methods */
public __construct()
public count(): int
public getIterator(): Iterator
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): void
}
Examples
예제 #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)
목차
- WeakMap::__construct — Constructs a new map
- WeakMap::count — Counts the number of live entries in the map
- WeakMap::getIterator — Retrieve an external iterator
- WeakMap::offsetExists — Checks whether a certain object is in the map
- WeakMap::offsetGet — Returns the value pointed to by a certain object
- WeakMap::offsetSet — Updates the map with a new key-value pair
- WeakMap::offsetUnset — Removes an entry from the map