Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is singleton in PHP?

Tags:

php

This question may be really a silly question for many. But, i could not find the exact answer for it.

What is singleton class in PHP?

I went through many tutorials, still do not understand exact meaning of it. What I understand is that, it cannot be instantiated more than once. The object will be shared. What does that really mean? Suppose the singleton is implemented for database connection, does it mean, that if 'A' is access the site and logging in. Meanwhile say 'B' tries to login and B will not be able to login until A logout and releases the object?

like image 472
karthik_spain Avatar asked Jul 20 '14 15:07

karthik_spain


People also ask

Why singleton class is used in PHP?

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.

What is singleton used for?

Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core java classes also, for example java.

What is singleton with example?

Example. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton.

What is meant by singleton pattern?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system.


2 Answers

  • Singleton can be used like a global variable.
  • It can have only one instance (object) of that class unlike normal class.
  • When we don't want to create a more than one instance of a class like database connection or utility library we would go for singleton pattern.
  • Singleton makes sure you would never have more than one instance of a class.
  • Make a construct method private to make a class Singleton.
  • If you don't want to instantiate a multiple copies of class but only one then you just put it in singleton pattern and you can just call methods of that class and that class will have only one copy of it in a memory even if you create another instance of it.
  • If user just wants to connect to database then no need to create a another instance again if the instance already exist, you can just consume first object and make the connection happen.

e.g.

<?php
    class DBConn {

        private static $obj;

        private final function  __construct() {
            echo __CLASS__ . " initializes only once\n";
        }

        public static function getConn() {
            if(!isset(self::$obj)) {
                self::$obj = new DBConn();
            }
            return self::$obj;
        }
    }

    $obj1 = DBConn::getConn();
    $obj2 = DBConn::getConn();

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

Output:

DBConn initializes only once
bool(true)

Object1 and Object2 will point to the same instance

            _______________________
           |                       |
$obj1 ---->|  Instance of DBConn   |<----- $obj2
           |_______________________| 

Hope that helps!! :)

like image 57
Hemangi Gokhale Avatar answered Oct 01 '22 09:10

Hemangi Gokhale


A singleton is a particular kind of class that, as you correctly said, can be instantiated only once.

First point: it isn't a PHP related concept but an OOP concept.

What "instantiated only once means?" It simply means that if an object of that class was already instantiated, the system will return it instead of creating new one. Why? Because, sometimes, you need a "common" instance (global one) or because instantiating a "copy" of an already existent object is useless.

Let's consider for first case a framework: on bootstrap operation you need to instantiate an object but you can (you have to) share it with other that request for a framework bootstrap.

For the second case let's consider a class that has only methods and no members (so basically no internal state). Maybe you could implement it as a static class, but if you want to follow design patterns, consider AbstractFactory) you should use objects. So, having some copy of the same object that has only methods isn't necessary and is also memory-wasting.

Those are two main reason to use singleton to me.

like image 21
DonCallisto Avatar answered Oct 01 '22 11:10

DonCallisto