As a common design pattern, the singleton pattern is widely used. So what is the best way to design a singleton?
Usually we write like this, and most of the examples that can be found on the Internet are like this:
Copy the code The code is as follows:
class A
{
protected static $_instance = null;
protected function __construct()
{
//disallow new instance
}
protected function __clone( ; new self();
}
return self::$_instance;
}
}
class B extends A
{
protected static $_instance = null;
}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);
Change __construct method Making it private ensures that this class cannot be instantiated by others. But an obvious problem with this way of writing is that the code cannot be reused. For example, we inherit A one by one:
Copy code
The code is as follows:
class B extends A{ protected static $_instance = null;}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);
The above code will Output:
Copy code
The code is as follows:
bool(true)The problem is with self, The reference of self is determined when the class is defined. That is to say, if A inherits B, its self reference still points to A. To solve this problem, the feature of late static binding was introduced in PHP 5.3. Simply put, static methods or variables are accessed through the static keyword. Unlike self, static references are determined at runtime. So we simply rewrite our code so that the singleton mode can be reused.
Copy code
The code is as follows:
class C{ protected static $_instance = null;
protected function __construct()
{
}
protected function __clone()
{
//disallow clone
}
public function getInstance()
{
if (static::$_instance = == null) {
static::$_instance = new static;
protected static $_instance = null;
}
$c = C::getInstance();
$d = D::getInstance();
var_dump($c === $d);
The above code output:
Copy code
The code is as follows:
bool(false)
In this way, the singleton mode can be implemented by simply inheriting and reinitializing the $_instance variable. Note that the above method can only be used in PHP 5.3. For previous versions of PHP, it is better to write a getInstance() method for each singleton class.
It should be reminded that although the singleton mode in PHP does not have the same thread safety issues as Java, you still need to be careful when using the singleton mode for stateful classes. Singleton mode classes will accompany the entire life cycle of PHP running, and are also an overhead for memory.
http://www.bkjia.com/PHPjc/802220.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/802220.html
TechArticle
As a commonly used design pattern, the singleton pattern is widely used. So what is the best way to design a singleton? Usually we write like this, and most of the examples that can be found on the Internet are...