MENU
WeakMap and WeakReference
A normal variable, array entry, or property holding an object counts as a reference to it, keeping it alive: PHP won't garbage-collect an object while anything still points to it. A WeakReference (added in PHP 7.4) is different — it points to an object without counting as a reference, so the object can still be destroyed as if the weak reference didn't exist. Create one with WeakReference::create($obj), and read the object back, while it is still alive, with ->get().<?php
class Foo {}
$obj = new Foo();
$ref = WeakReference::create($obj);
var_dump($ref->get() instanceof Foo);
unset($obj);
gc_collect_cycles();
var_dump($ref->get());
?>bool(true)
NULL
<?php
class Foo {}
$map = new WeakMap();
$obj = new Foo();
$map[$obj] = 'data for obj';
echo "Count before: ", count($map), "\n";
unset($obj);
gc_collect_cycles();
echo "Count after: ", count($map), "\n";
?>Count before: 1
Count after: 0