メソッドが親クラスにある場合、呼び出されているクラスのインスタンスを返すにはどうすればよいですか。
例えば。B
以下の例では、 if I callのインスタンスを返すにはどうすればよいB::foo();
ですか?
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();
}
}