创建一个被调用的类的新实例而不是父类

Ada*_*dam 2 php inheritance static

当方法在父类中时,如何返回被调用的类的实例.

例如.在下面的示例中,B如果我调用,如何返回实例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.
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做,但有一个更简洁的方式:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)