Weak References
A weak reference is a link to an object that does not keep the object alive. The object can still vanish while the weak reference points at it.
A weak reference reads a live object
The create method builds a weak reference to the note object. The get method hands the object back, and its text prints.
<?php
class Note {
public string $text = "Draft ready";
}
$note = new Note();
$weak = WeakReference::create($note);
echo $weak->get()->text . "\n";The object vanishes under the weak reference
The unset line drops the only strong name for the object. The collector runs, and the get method now hands back null.
<?php
class Note {
public string $text = "Draft ready";
}
$note = new Note();
$weak = WeakReference::create($note);
unset($note);
gc_collect_cycles();
var_dump($weak->get());A WeakMap forgets a vanished key
Two objects become keys in a WeakMap, and the count prints 2. One object is unset and the collector runs, so the count prints 1 and the other entry still reads.
<?php
class Item {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
$map = new WeakMap();
$a = new Item("pen");
$b = new Item("cup");
$map[$a] = "first";
$map[$b] = "second";
echo count($map) . "\n";
unset($a);
gc_collect_cycles();
echo count($map) . "\n";
echo $map[$b] . "\n";Example
<?php
class Page {
public string $title;
public function __construct(string $title) {
$this->title = $title;
}
}
$home = new Page("Home");
$help = new Page("Help");
$cache = new WeakMap();
$cache[$home] = "cached home page";
$cache[$help] = "cached help page";
echo count($cache) . "\n";
unset($help);
gc_collect_cycles();
echo count($cache) . "\n";
echo $cache[$home] . "\n";Key points
- WeakReference::create builds a weak reference from an object.
- The get method hands back the object while the object still lives.
- The get method hands back null once the object is gone.
- The gc_collect_cycles function collects objects that no strong name keeps alive.
- A WeakMap is a map whose keys are objects.
- A WeakMap entry vanishes when its key object vanishes.
In this example, two page objects become keys in a WeakMap that stands in for a cache. The count prints 2 while both pages live. The help page is unset and the collector runs, so the count prints 1 and the home entry still reads back.
Note
A weak reference lets a program watch an object without owning it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the get method of a weak reference hand back after its object is gone and the collector has run?