Singleton pattern is described as a grand daddy of all design patterns. The Singleton pattern is a design pattern which restricts instantiation of a class to one single object. In other words we can say Singleton is a fancy name for a GLOBAL Variable.
The best example for singleton pattern is Database class . You really dont want more than one instance of Database connect in the life cycle of your script. The way we do that that is that we dont make it possible to create a new instance of the class using NEW.
Class DB
{
private __construct()
{
//PRIVATE
}
}
$db=new DB();
IF we run this script we get FATAL error saying constructor of the class DB is private.
So the way we can create instance of this class is by creating a private static variable.
Class DB{
private static $instance;
private __construct()
{
//PRIVATE
}
}
$db=new DB();
Then we create a public static function that gets us the instance
Class DB{
private static $instance
private __construct()
{
//PRIVATE
}
public static function getinstance()
{
return DB::$instance = new DB();
}
public function query()
{
return “select * from tablename”;
}
}
$db=DB::getInstance();
echo $db->query();
This will return “select * from tablename”.
But if you see the above code , every time you call query function it will always create new instance of that class .
So we our new code is
Class DB{
private static $instance
private __construct()
{
//PRIVATE
}
public static function getinstance()
{
if(!isset(DB::$instance))
{
DB::$instance = new DB();
}
return DB::$instance;
}
public function query()
{
return “select * from tablename”;
}
}
$db=DB::getInstance();
echo $db->query();










