Weak References

The new operator creates an object based on a class and returns a reference to this new instance that can be assigned to a variable. The object can then be accessed through that variable. As long as a variable holds a reference to an object, it is kept in memory. When no variable references an object anymore, the object will be destroyed. This is the responsibility of PHP’s garbage collector.

Caching in general and the Identity Map pattern in particular are use cases where it may make sense to have a variable that holds a reference to an object without having that reference prevent the object from getting destroyed by the garbage collector. This is where weak references come into play.

PHP provides the WeakReference class for storing a weak reference to an object. The weak reference is created using the static method WeakReference::create(), and the referenced object can be accessed through WeakReference::get():

$o = new stdClass;
$r = WeakReference::create($o);

var_dump(isset($o));
var_dump($o instanceof stdClass);

var_dump(isset($r));
var_dump($r->get() instanceof stdClass);

unset($o);

var_dump(isset($o));
var_dump(isset($r));
var_dump($r->get());

Executing the code shown above will print the output shown below:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
NULL

WeakReference::get() returns null when the object that is weakly referenced no longer exists.

The WeakReference class is final. WeakReference objects cannot be serialized and no properties can be set on them:

$o = new stdClass;
$r = WeakReference::create($o);

$r->foo = 'bar';

Executing the code shown above will print the error shown below:

Uncaught Error: WeakReference objects do not support
properties in ...
$o = new stdClass;
$r = WeakReference::create($o);

serialize($r);

Executing the code shown above will print the error shown below:

Uncaught Exception: Serialization of 'WeakReference'
is not allowed in ...