A singleton class is a class that can have only one object (an instance of the class) at a time.
The instance is created when the static method is first invoked.
/**
* Lazy load Simple example of Singleton design pattern
*/
final class Singleton
{
/**
* Variable for store instance
*
* @var Singleton $instance
*/
private static $instance = null;
/**
* The constructor __construct() is declared as protected
* to prevent creating a new instance outside of the class
* via the new operator.Constructor is private
*/
private function __construct()
{
// some code, connect to db etc.
}
/**
* The magic method __clone() is declared as private
* to prevent cloning of an instance of the class via the clone operator.
*/
private function __clone()
{
//
}
/**
* The magic method __wakeup() is declared as private
* to prevent unserializing of an instance of the class
* via the global function unserialize()
*/
private function __wakeup()
{
//
}
/**
* Create instance of object
* if it is not exist or return existed
*
* @return Singleton
*/
static public function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new Singleton();
}
return self::$instance;
}
}