PHP WeakReference class

PHPServer Side ProgrammingProgramming


With Weak references, it is possible to retain a reference to an object which does not prevent the object from being destroyed. Implementing cache like structures can be done by Weak reference.

A weak reference is similar to a normal reference, except that it doesn’t prevent the garbage collector from collecting the object. If strong references to that object are not found, it will be immediately removed frommemory. This way it is possible to implement most of the benefits of a cache, with no memory issues.

WeakReference class has been introduced in PHP 7.4. Before this version, same effect used to be obtained by weakref extension. The WeakReference class has following structure


WeakReference {
   /* Methods */
   public __construct ( void )
   public static create ( object $referent ) : WeakReference
   public get ( void ) : ?object


public WeakReference::__construct ( void ) — disallow instantiation of the WeakReference class. It can be instantiated with the factory method WeakReference::create().

public static WeakReference::create ( object $referent ) : WeakReference — Creates a new WeakReference.

public WeakReference::get ( void ) : ?object — Gets a weakly referenced object. If the object has already been destroyed, NULL is returned.

Generator Example

Following example has object of myclass. WeakReference to its object shows one reference. Object is then unset. Now WeakReference returns NULL


class myclass{
   function Hello(){
      echo "Hello";
$obj = new myclass();
$ref = WeakReference::create($obj);


Above program shows following output

object(myclass)#1 (0) {
Published on 21-Sep-2020 15:36:26