Open In App

How to create singleton design pattern in PHP 5 ?

Improve
Improve
Like Article
Like
Save
Share
Report

When you don’t want to have more than a single instance of a given class, then the Singleton Design Pattern is used and hence the name is – Singleton. 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. 
Normally when using various objects & classes, define the class only once and then create many objects and instances in our application with each object/instance having its own property. For example, when we are having a class name called “Student” with three attributes – “Fore_Name”, “Middle_Name” and “Sur_Name”. Each instance of that “Student” might or might not be having different values for “Fore_Name”, “Middle_Name” and “Sur_Name”. But if we use a singleton design pattern, there could never be more than a single instance of a given class ever in that given point of the program. The reason is quite simple. Suppose if we want our application to only ever have just one connection in a database, then we have to create a singleton class called “DataBase Connector” whose job is to ensure that there would be only a single DataBase connection in our program. Further meaning that we can access that particular instance quite globally so that we wouldn’t have to get the database connection object between functions get passed so that it could be accessed from each and every place on earth.
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.
Below program illustrates the Singleton Design Pattern:
Example: 
 

php




<?php
 
class DataBaseConnector {
                 
    private static $obj;
                 
    private final function __construct() {
        echo __CLASS__ . " initialize only once ";
    }
     
    public static function getConnect() {
        if (!isset(self::$obj)) {
            self::$obj = new DataBaseConnector();
        }
         
        return self::$obj;
    }
}
 
$obj1 = DataBaseConnector::getConnect();
$obj2 = DataBaseConnector::getConnect();
 
var_dump($obj1 == $obj2);
?>


Output

DataBaseConnector initialize only once bool(true)
 

Last Updated : 06 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads