目前的一个项目有几个模块需要实现单例模式,于是想实现一个Singleton基类来使这些模块通过继承该基类实现Singleton。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php
class Singleton
{
protected static $instances;
public static function getInstance()
{
if(!isset(self::$instances)) {
self::$instances = new __CLASS__;
}
return self::$instances;
}
protected function __construct() { }
protected function __clone() { }
} |
这是一个Singleton的PHP实现,然而这时希望通过如下代码使Database类实现Singleton是不可行的:
|
1 2 |
<?php
class Database extends Singleton { } |
因为__CLASS__获得的永远只是父类(Singleton)而不是子类,所以无法获知子类类信息,自然也就无法实现子类的单例。
PHP5.3 提供了get_called_class()函数,用过此函数可以实现Singleton的继承。
其它实现方式
为了能在PHP5.3以前实现Singleton的继承,我们可以定义一个静态数组来维护类的实例,定义以及使用方法如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php
class Singleton
{
protected static $instances = array();
public static function getInstance($className)
{
if(!isset(self::$instances[$className])) {
self::$instances[$className] = new $className;
}
return self::$instances[$className];
}
protected function __construct() { }
protected function __clone() { }
}
class Database extends Singleton
{
public function hello()
{
echo 'hello';
}
}
Singleton::getInstance('Database')->hello(); |