What are Weak Maps in PHP?

PHPServer Side ProgrammingProgramming

Weak Maps were added in PHP 7.4. It can be used to remove or delete objects when the cache refers to objects entity classes. It references to those objects, which does not avoid objects from memory garbage collected. In PHP 8, weak maps allow us to store random data linked to objects, without leaking any memory.

In other words, a weak map in PHP 8 is a group of objects in which keys weakly reference. A weak map uses a class to create an object which can be used as a key, which can help to remove and destroy the weak map if there are no further references. In the long-run process, it can avoid memory leaks, which ultimately improves performance.

We can say a weak map works as an automatic garbage collection process. Whenever a variable is deleted, PHP will check if any variables are still referencing that object. If the variable is not referencing, then PHP will delete that object safely. This process is called garbage collection.

Example: Weak Maps PHP 8

<?php
   class WeakExample {
      public WeakMap $cache;
      public function __construct() {
         $this->cache = new WeakMap();
      }
      public function getCaching(object $obj) {
         return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);
      }
      public function computeSomethingExpensive(object $obj) {
         print_r("Object called");
         return rand(1, 100);
      }
   }
   $cacheObject = new stdClass;
   $obj = new WeakExample;

   $obj->getCaching($cacheObject);
   $obj->getCaching($cacheObject);
   print_r(count($obj->cache));

   unset($cacheObject); // unsetting the objects and Weak Maps frees up memory
   print_r(count($obj->cache));
?>

Output

Object called 1 0
raja
Published on 01-Apr-2021 06:38:52
Advertisements