The WeakReference class

(PHP 7 >= 7.4.0, PHP 8)

Introduction

Weak references allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures.

WeakReferences cannot be serialized.

Class synopsis

final class WeakReference {
/* Methods */
public __construct()
public static create(object $object): WeakReference
public get(): ?object
}

WeakReference Examples

Example #1 Basic WeakReference Usage

<?php
$obj
= new stdClass;
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset(
$obj);
var_dump($weakref->get());
?>

The above example will output something similar to:

object(stdClass)#1 (0) {
}
NULL

Table of Contents

add a note add a note

User Contributed Notes 1 note

up
-42
Sandor Toth
4 years ago
You might consider to use WeakReference in your Container class. Don't forget to create the object into a variable and pass the variable to WeakReference::create() otherwise you going to ->get() null.

Consider as wrong solution, which returns null
<?php
/**
* @return App
*/
public static function app() : App
{
    if (!static::
$app) {
       static::
$app = WeakReference::create(new App());
    }

    return static::
$app->get();
}
?>

Consider as GOOD solution, which returns App instance
<?php
/**
* @return App
*/
public static function app() : App
{
    if (!static::
$app) {
      
$app = new App();
       static::
$app = WeakReference::create($app);
    }

    return static::
$app->get();
}
?>
To Top