What is Singleton? explain with PHP example
In SIngleton design pattern
Only a single object will be created and i.e available all across the application.
Singleton Pattern ensures that a class has only one instance and provides a global point to access it. It ensures that only one object is available all across the application in a controlled state. Singleton pattern provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.
xxxxxxxxxx
// General singleton class.
class Singleton {
// Hold the class instance.
private static $instance = null;
// The constructor is private
// to prevent initiation with outer code.
private function __construct()
{
// The expensive process (e.g.,db connection) goes here.
}
// The object is created from within the class itself
// only if the class has no instance.
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new Singleton();
}
return self::$instance;
}
}
// sesond example:
<?php
class database {
public static $connection;
private function __construct(){
echo "connection created";
}
public function connect(){
if(!isset(self::$connection)){
self::$connection = new database();
}
return self::$connection;
}
}
$db = database::connect();
//$db2 = database::connect(); //will not work if we try to initiate object again.
?>
xxxxxxxxxx
<?php
/*singleton design pattern should have
private static variable
private constructor method
public static method return class single instance */
class clsSingleTon
{
private static $conn=null;
private function __construct()
{
print "Instance Created \n";
}
public static function setConn()
{
if(self::$conn == null)
{
self::$conn = new static();
}else{
print "Instance Already Created \n";
}
return self::$conn;
}
}
$obj = clsSingleTon::setConn();
//$obj = clsSingleTon::setConn();
//if we create second Instance then it will say already created
?>