Tag Archives: php5

Singleton Design Pattern in PHP

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

The following code is a simple implementation:



class Database
{
    // A static property to hold the single instance of the class
    private static $instance;

    // The constructor is private so that outside code cannot instantiate
    private function __construct() { }

    // All code that needs to get and instance of the class should call
    // this function like so: $db = Database::getInstance();
    public function getInstance()
    {
        // If there is no instance, create one
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    // Block the clone method
    private function __clone() {}
}

// To use, call the static method to get the only instance
$db = Database::getInstance();


Pros and Cons of Singeleton Design Pattern :

pro : You know you have the same instance available at all times.
con : One and only one instance is all you get.
pro : Instantiate itself for you so all you need to do is get it.
con : Autoinstantiation diminishes flexibility of argument passing.
pro : Since it is singeleton it can replace global variable declaration.
con : Since it is singeleton it can replace global variable declaration.