Lazy Initialization Design Patterns in PHP
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 |
|
Problem |
Solution |
|
|
<?php 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"; } } Fruit::getFruit('Apple'); Fruit::printCurrentTypes(); Fruit::getFruit('Banana'); Fruit::printCurrentTypes(); Fruit::getFruit('Mango'); Fruit::printCurrentTypes();?>
OUTPUT:
Number of instances made: 1
Apple
Number of instances made: 2
Apple
Banana
Number of instances made: 3
Mango
Apple
Banana

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first Fifteen years a number of leadership positions at AmarBebsha Ltd as a CTO, Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now I’m a founder and CEO of TechBeeo Software Company 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.