Implementation of Singleton Design Pattern in PHP5

Implementation of Singleton Design Pattern in PHP5

Singleton Pattern:
- It ensures class has only one instane.in other words it just restricts instantiation of a class to one object.

Implementation:
Following code implements singleton.

/* Singleton */
class One{
public static function getObject(){
static $db = null;

if ( $db == null )
$db = new One();

return $db;
}
private function __construct(){
;
}
public function display(){
echo “This is Class One”;
}
}

One::getObject()->display();
/* Singleton */

- here we are making constructor is private.so we can’t create object outside the class.
- so we can create the object using static function only.Her getObject() function creates object for you.
- getObject() allows us to create one object only.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.