Php object-oriented – singleton pattern
Guaranteed class has only one instance
1. How to solve the problem that a class can be instantiated infinitely?
New can be instantiated once. How to limit it? Users cannot use new unlimited times?
Private the constructor. All external new operations fail
class MySQLDB
{
private function __construct()
{
}
}
2. Once the constructor is privatized, it means that the class cannot be instantiated outside the class. But it can be instantiated within the class.
Add a public static method, call the method through the class, and perform new operations within the method.
class MySQLDB
{
private function __construct()
{
}
public static function getInstance()
{
return new MySQLDB;
}
}
$o = MySQLDB::getInstance();
At this time, when the user needs an object of this class, the code in the method will be executed. Therefore, we can limit the user's operation of obtaining the object by improving the logic within the method.
3. In the above method, use the following logic: make a judgment every time it is executed to determine whether the class has instantiated the object. If it has instantiated the object, directly return the instantiated object. If not instantiated, instantiate a new one and return.
How to judge?
Save this object when it is instantiated.
Example:
class MySQLDB
{
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if(!self::$instance instanceof self)
{
self::$instance= new self;
}
return self::$instance;
}
}
4. Cloning can also get new objects, so cloning needs to be restricted.
Private __clone() method
class MySQLDB
{
private static $instance;
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance()
{
if(!self::$instance instanceof self)
{
self::$instance= new self;
}
return self::$instance;
}
}