আগামী ৩০ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

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

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
<?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 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 *