Lazy Initialization Design Patterns in PHP

Lazy Initialization Design Patterns in PHP

Lazy Initialization Pattern

Lazy evaluation
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
This is typically accomplished by maintaining a flag indicating whether the process has taken place. Each time the desired object is summoned, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot.

Lazy Initialization Method: problem & solution



  • You want to delay the creation of an instance or an expensive operation until the first time it is needed
  • You want the operation to be executed only when and if necessary
  • The Lazy Initialization pattern delays the creation of an object or the execution of an expensive process until the first time it is needed
 header('Content-type:text/plain; charset=utf-8');
 class Fruit {
 private $type;
 private static $types = array();
 private function __construct($type) {
 $this->type = $type;
 public static function getFruit($type) {
 // Lazy initialization takes place here
 if (!array_key_exists($type, self::$types)) {
 self::$types[$type] = new Fruit($type);
 return self::$types[$type];
 public static function printCurrentTypes() {
 echo 'Number of instances made: ' . count(self::$types) . "\n";
 foreach (array_keys(self::$types) as $key) {
 echo "$key\n";
 echo "\n";

Number of instances made: 1
Number of instances made: 2
Number of instances made: 3

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

Leave a Reply

Your email address will not be published. Required fields are marked *