@ 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.
(PHP 8)
WeakMap nesneleri anahtar olarak kabul eden bir haritadır (veya sözlüktür). Ancak, SplObjectStorage'dan farklı olarak, WeakMap anahtarındaki nesne, nesnenin gönderim sayısına katkıda bulunmaz. Yani, herhangi bir noktada bir nesneye kalan tek gönderim bir WeakMap anahtarı ise, nesne çöp olarak toplanacak ve WeakMap'ten kaldırılacaktır. Birincil kullanım durumu, nesneden daha uzun yaşaması gerekmeyen bir nesneden türetilen verilerin arabelleklerini oluşturmak içindir.
WeakMap sınıfı ArrayAccess, Iterator ve Countable arayüzlerini gerçekler, bu yüzden çoğu durumda ilişkili bir dizi gibi kullanılabilir.
Örnek 1 - Weakmap kullanım örneği
<?php
$wm = new WeakMap();
$o = new stdClass;
class A {
public function __destruct() {
echo "Öldü!\n";
}
}
$wm[$o] = new A;
var_dump(count($wm));
echo "Yok ediliyor...\n";
unset($o);
echo "İşi bitti\n";
var_dump(count($wm));
Yukarıdaki örneğin çıktısı:
int(1) Yok ediliyor... Öldü! İşi bitti int(0)
@ 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.
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.
<?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