当方法位于父类中时,如何返回被调用类的实例。创建被调用类的新实例而不是父类
例如,在下面的示例中,如果我拨打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)不能被实例化。 –
它是一个例子。 – Adam