@ 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 は、 オブジェクトをキーとして受け入れるマップ(辞書)です。 SplObjectStorage と似ていますが、 WeakMap のキーとなるオブジェクトは、 オブジェクトのリファレンスカウントが更新されません。 つまり、WeakMap のキーとなっているオブジェクトだけが唯一の残された参照だった場合、 オブジェクトはガベージコレクションの対象となり WeakMap から削除されます。 WeakMap の用途は、 長く生き残る必要がないオブジェクトから派生した、 データのキャッシュを作ることです。
WeakMap は ArrayAccess, Iterator, Countable を実装しています。 よって、ほとんどのケースで、 連想配列と同じやり方で操作できます。
例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)
@ 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
$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