class A{
private static $instance;
public static function getInstance(){
if(!(self::$instance instanceof self))
self::$instance = new self();
return self::$instance;
}
public function doStuff(){
echo 'stuff';
}
}
class B extends A{
public function doStuff(){
echo 'other stuff';
}
}
A::getInstance()->doStuff(); // prints "stuff"
B::getInstance()->doStuff(); // prints "stuff" instead of 'other stuff';
我做错了什么?
为什么 B 类不运行它的功能?
最佳答案
看getInstance
中的代码:
if(!(self::$instance instanceof self))
self::$instance = new self();
所有这些 self
都指向 A
,而不是被调用的类。 PHP 5.3 引入了一个叫做 "late static binding" 的东西。 ,它允许您指向被调用的类,而不是代码所在的类。您需要使用 static
关键字:
class A{
protected static $instance; // converted to protected so B can inherit
public static function getInstance(){
if(!(static::$instance instanceof static))
static::$instance = new static(); // use B::$instance to store an instance of B
return static::$instance;
}
public function doStuff(){
echo 'stuff';
}
}
不幸的是,如果您至少没有 PHP 5.3,这将失败。
关于php - 在 PHP 中扩展一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419224/