class A {
protected static $_instance = null;
protected function __construct() {}
protected function __clone() {}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self();
}
return self::$_instance;
}
}
class B extends A {
protected static $_instance = null;
}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b); // true —— B 復用了 A 的實例!
問題在 self:編譯期綁定到定義類 A,導致子類共享父類實例。
將 self 替換為 static,運行期根據調用類解析:
class Singleton {
protected static $_instance = null;
protected function __construct() {}
protected function __clone() {}
public static function getInstance() {
if (static::$_instance === null) {
static::$_instance = new static(); // 關鍵:new static()
}
return static::$_instance;
}
}
class ServiceA extends Singleton {
protected static $_instance = null; // 必須重新聲明
public function say() { echo "ServiceA\n"; }
}
class ServiceB extends Singleton {
protected static $_instance = null;
public function say() { echo "ServiceB\n"; }
}
$sa = ServiceA::getInstance();
$sb = ServiceB::getInstance();
var_dump($sa === $sb); // false —— 各自獨立實例
$sa->say(); // ServiceA
$sb->say(); // ServiceB
static::$_instance 與 new static() 實現運行期綁定。protected static $_instance = null;,否則仍共享父類靜態屬性。__construct、__clone、__wakeup 設為 protected/private 防止外部實例化/克隆/反序列化。getInstance。setInstance() 或使用工廠模式。