PHP WeakReference class

PHPServer Side ProgrammingProgramming

Introduction

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

Syntax

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

Methods

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

Example

<?php
class myclass{
   function Hello(){
      echo "Hello";
   }
}
$obj = new myclass();
$ref = WeakReference::create($obj);
var_dump($ref->get());
unset($obj);
var_dump($ref->get());
?>

Output

Above program shows following output

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