Call us now! 8130-90-5320 | info@lohiyait.com | Find our Location
Singleton design pattern in php
admin February 3, 2021 Category: OOPS CONCEPTS, PHP Views: 1012
singleton design pattern

Singleton Pattern ensures that a class has only one instance and provides a global point to access it. It ensures that only one object is available all across the application in a controlled state. Singleton pattern provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.

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

The major reason to use the Singleton Design Pattern is that we can use the Singleton Design Pattern object globally and unlike other normal classes, it could only contain one kind of object or one kind of instance. Sometimes, when there is an object that is created only once like the DataBase connection, then the use of Singleton is much more preferable. But note that the constructor method needs to be in private to make the class Singleton.

<?php

Example
class DataBase {

private static $obj;

private final function __construct() {
echo __CLASS__ . ” initialize only once “;
}

public static function getConnect() {
if (!isset(self::$obj)) {
self::$obj = new DataBase();
}

return self::$obj;
}
}

$obj1 = DataBase::getConnect();
$obj2 = DataBase::getConnect();

var_dump($obj1 == $obj2);
?>