Singleton Pattern in PHP

Singleton design pattern is used to control the instantiation of a class to an Object. The singleton pattern is implemented by creating the class with a method that creates an instance if one does not exists and the constructor of the class is private.

We can implement this in PHP-5 as followings

<?php

class Singleton {

// object instance

private static $instance;

//constructor
private function __construct() {}

//clone
private function __clone() {}

//make instance
public static function getInstance() {

if (self::$instance === null) {//checking the previous instance

self::$instance = new self;

}

return self::$instance;

}

//the other methods of this class

public function doAction() {

}

}

?>

<?php

//usage

Singleton::getInstance()->doAction();

?>

In this example we can see that a static variable $instance is declared to hold the instance of the class. Also the constructor and clone method is private, this ensure the controlling of making the new object of that class.

After that we make a public function getInstance to make an instance of the class. This function return a new instance if no instance of the class is not exists, if exists this return that instance.

AND the uses is simple just use $class_name->getInstance() to make a new instance of the class.

Thanks

2 Comments »

  1. vailo said

    This was useful indeed! Good explaination and good example!

  2. Tapos said

    thanks Vailo for reading this article and nice comment

RSS feed for comments on this post · TrackBack URI

Leave a Comment