【发布时间】:2012-11-23 16:12:54
【问题描述】:
当方法在父类中时,如何返回被调用类的实例。
例如。在下面的示例中,如果我调用B::foo();,如何返回B 的实例?
abstract class A
{
public static function foo()
{
$instance = new A(); // I want this to return a new instance of child class.
... Do things with instance ...
return $instance;
}
}
class B extends A
{
}
class C extends A
{
}
B::foo(); // Return an instance of B, not of the parent class.
C::foo(); // Return an instance of C, not of the parent class.
我知道我可以这样做,但有没有更简洁的方法:
abstract class A
{
abstract static function getInstance();
public static function foo()
{
$instance = $this->getInstance(); // I want this to return a new instance of child class.
... Do things with instance ...
return $instance;
}
}
class B extends A
{
public static function getInstance() {
return new B();
}
}
class C extends A
{
public static function getInstance() {
return new C();
}
}
【问题讨论】:
-
您编写的代码应该给出致命错误。抽象类 (A) 无法实例化。
标签: php inheritance static