为什么不起作用? 我想创建单例来连接到数据库、自动加载器、路由器。
static $singleton = null;
public function __construct(){
if(empty(self::$singleton)){
self::$singleton = new self;
return self::$singleton;
}
return self::$singleton;
}
在 php 方法 __construct 中总是返回类的实例,你不能操作返回值。
要做你想做的事,你应该使用 private __conctruct() 并用你的代码创建下一个方法,例如 public static getInstance() :
static $singleton = null;
public function getInstance(){
if(empty(self::$singleton)){
$class = get_called_class();
self::$singleton = new $class;
}
return self::$singleton;
}
就是这样:
class Singleton {
private static $singleton = null;
private function __construct() {}
private function __clone() {}
private function __sleep() {}
private function __wakeup() {}
public static function getInstance(){
if(empty(self::$singleton)){
self::$singleton = new self;
return self::$singleton;
}
return self::$singleton;
}
}
不要使用构造函数,创建一个单独的方法:
public static function getInstance ()
{
if (is_null(self::$singleton)) {
self::$singleton = new self();
}
return self::$singleton;
}
创建对象时会调用构造函数 - 在这种情况下,无论调用多少次
getInstance()
,该对象都应该只创建一次。