User Tools

Site Tools


Singleton Pattern

THE SINGLETON PATTERN is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

First example:

class Example {
static $instance;
 // A private constructor; prevents direct creation of object
private function __construct () {}
//deny cloning of singleton objects
private function __clone() {}
// singleton method
public static function init () {
    if (!Example::$instance instanceof self) {
        Example::$instance = new self();
    return Example::$instance;
// custom function may follow
public function do_something () {
    echo "I did something";
} // end of class

Usage for first example:

$ob = Example::init();
$ob -> do_something(); //will display I did something

Second example:

class DatabaseConnection {
static $db = null;
private $_handle = null;
private function __construct() {
    $this->_handle = mysql_connect('localhost', 'root', '') or die (mysql_error());
public static function init() {
    if ( !DatabaseConnection::$db instanceof self )
        DatabaseConnection::$db = new self();
    return DatabaseConnection::$db;
public function handle() {
    echo $this->_handle;
} // end of class

Usage for second example:

$ob = DatabaseConnection::init();
$ob -> handle(); //will display the same Resource (eg Resource id #2)

php/singleton.txt · Last modified: 2013/03/16 17:40 (external edit)