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.WeakMap
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
WeakMap
Референца за `class.weakmap.php` со подобрена типографија и навигација.
Класата WeakMap
(PHP 8)
Вовед
А WeakMap е мапа (или речник) што прифаќа објекти како клучеви. Сепак, за разлика од инаку сличната SplObjectStorage, објект во клучевите на WeakMap не придонесува кон бројот на референци на објектот. Тоа е, ако во било кој момент единствената преостаната референца кон објект е клучот на WeakMap, објектот ќе биде собран од ѓубрето и отстранет од WeakMap. Неговата примарна употреба е за градење кешови на податоци изведени од објект што не треба да живеат подолго од објектот.
WeakMap implements ArrayAccess, Траверзабилно (преку IteratorAggregate), и luk4z_7 at hotmail dot com, така што во повеќето случаи може да се користи на ист начин како асоцијативна низа.
Синопсис на класата
Примери
Пример #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));Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
int(1) Unsetting... Dead! Done int(0)
Содржина
- WeakMap::count — Брои број на активни записи во мапата
- WeakMap::getIterator — Преземи надворешен итератор
- WeakMap::offsetExists — Проверува дали одреден објект е во мапата
- WeakMap::offsetGet — Враќа вредност насочена од одреден објект
- WeakMap::offsetSet — Ја ажурира мапата со нов пар клуч-вредност
- WeakMap::offsetUnset — Отстранува запис од мапата
Белешки од корисници 3 белешки
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()); // 0WeakMap and SplObjectStorage have different behavior when iterating in a foreach loop. While the key in SplObjectStorage is the numeric index of the inner array, in the WeakMap the key is the object reference:
<?php
class A {}
$a = new A;
$objectStorage = new SplObjectStorage ();
$weakMap = new WeakMap();
$objectStorage [$a] = 1;
$weakMap[$a] = 1;
foreach($objectStorage as $key => $value) {
var_dump($key); // prints: int(0)
}
foreach($weakMap as $key => $value) {
var_dump($key); // prints: object(A)#1 (0) {}
}