Implementing the Singleton pattern in PHP

In short, the Singleton Pattern is a design pattern used when we want only ONE instance of a class to be initialized. This is useful in CPU/Memory intensive classes, such as database handle abstractions.

The Singleton Pattern is a pretty fundamental pattern, worth learning about, if you aren’t already aware. It’s characterized by a private constructor, which can only be called by class member methods, and a public static accessor method, to return a reference to the object.

Here is a quick example of how it can be implemented in PHP (There are other ways, as well).

class Singleton {

    private static $__instance;
    protected $_value;

    private function __construct() {
        $this->_value = rand();
    }

    public static function getInstance() {
        if(!isset(self::$__instance)) {
            self::$__instance = new Singleton();
        }
        return self::$__instance;
    }

    public function display() {
        echo $this->_value . "<br />";
    }

}

Use it like this:

$foo = Singleton::getInstance();
$foo->display();

$bar = Singleton::getInstance();
$bar->display();

Leave a Reply