这里解释了单身人士: http://en.wikipedia.org/wiki/Singleton_pattern#PHP_5。 我想使用单例类作为超类,并将其扩展到其他应该是单例的类中。问题是,超类构成了自身的实例,而不是子类。知道如何让Superclass创建子类的实例吗?
class Singleton {
// object instance
private static $instance;
protected function __construct() { }
public function __clone() { }
public function __wakeup() { }
protected static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
if(self::$instance instanceof Singleton)
echo "made Singleton object<br />";
if(self::$instance instanceof Text)
echo "made Test object<br />";
}
return self::$instance;
}
}
class Test extends Singleton {
private static $values=array();
protected function load(){
$this->values['a-value'] = "test";
}
public static function get($arg){
if(count(self::getInstance()->values)===0)
self::getInstance()->load();
if(isset(self::getInstance()->values[$arg]))
return self::getInstance()->values[$arg];
return false;
}
}