# Weak References

> Section in “New and Extended Functionality › Language Features” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/language-features/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()`:

``` php
$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:

``` php
$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 ...

``` php
$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 ...

---

Previous: [Combined Comparison Operator](https://php7explained.com/new-and-extended-functionality/language-features/combined-comparison-operator/index.html.md) | Next: [Numeric Literal Separator](https://php7explained.com/new-and-extended-functionality/language-features/numeric-literal-separator/index.html.md)
