1 min read

PHP Weak References

A weak reference is a type of reference that does not prevent an object from being destroyed by the garbage collector. This is in contrast to a regular (strong) reference, which keeps the object alive as long as the reference exists.

Weak references are useful for implementing caches or mappings to objects that you don't want to keep in memory just because they are in the cache.

Creating a Weak Reference

You can create a weak reference using the WeakReference class.

<?php
class MyClass {
    public function __destruct() {
        echo "MyClass instance is being destroyed.\n";
    }
}

$obj = new MyClass();
$weakRef = WeakReference::create($obj);

// The object is still accessible through the weak reference
var_dump($weakRef->get());

// Unsetting the object will allow the garbage collector to destroy it
unset($obj); 

// At this point, the garbage collector may or may not have run.
// If it has, get() will return null.
var_dump($weakRef->get());
?>

Use Cases

  • Caching: You can use weak references to cache objects without preventing them from being garbage collected.
  • Observer Pattern: To avoid memory leaks where an observer is unintentionally kept alive by the subject it's observing.
  • Circular References: While PHP's garbage collector can handle circular references, weak references can provide a more explicit way to manage them.

Weak references were introduced in PHP 7.4.