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.
