PHP实现Singleton
Posted on 2011-06-17
什么是Singleton
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
目前的一个项目有几个模块需要实现Singleton,于是想实现一个Singleton基类来使这些模块通过继承该基类实现Singleton。
<?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是不可行的:
<?php
class Database extends Singleton { }
因为__CLASS__获得的永远只是父类(Singleton)而不是子类,所以无法获知子类类信息,自然也就无法实现子类的单例。
PHP5.3 提供了get_called_class()函数,透过此函数可以实现Singleton的继承。
其它实现方式
为了能在PHP5.3以前实现Singleton的继承,我们可以定义一个静态数组来维护类的实例,定义以及使用方法如下:
<?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();