singleton class in oops php design patterns

Learn Online singleton class in oops php design patterns:

 

singleton class in oops php design patterns

Singleton is the design patterns of PHP in OOPs concept , It is special kind of class that can be instantiated only once. if the object of that class already instantiated then it returns instead of creating new one.

There are some reason to use singleton as I feel :

we can used Singleton object globally.

It can have only one instance (object) of this class unlike another normal class.

In some case , if we need only once created object like database connection , then singleton is more preferable.

constructor method should be private to make a class Singleton.

ex :

<?php

class DBConnect {

 

private static $obj;

 

private final function __construct() {

 echo __CLASS__ . " initialize only once ";

}

 

public static function getConnect() {

if(!isset(self::$obj)) {

self::$obj = new DBConnect();

}

return self::$obj;

}

}

 

 $obj1 = DBConnect::getConnect();

 $obj2 = DBConnect::getConnect();

 

 var_dump($obj1 == $obj2);

?>

 

Output:

DBConnect initializes only once

bool(true)

Object1 and Object2 points to the same instance of given single ton class

| |

$obj1 —->| Instance of DBConnect |<—– $obj2

|_______________________|

 

Leave a Reply

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