通过继承的静态方法创建继承类的新实例

时间:2017-11-27 09:53:40

标签: php inheritance

我的课程中有一种方法可以创造一种新的自我。执行。

class foo {
    private $id;

    public function __construct( $id ) {
        $this->id = $id;
    }

    public static function byId( $id ) {
        return new self( $id );
    }  

}

现在我想使用foo中的byId方法并在bar中使用它,通过这样做

class bar extends foo {
    public function test() {
        echo "test";
    }
}  

现在我应该可以执行bar :: byId(id),但是这将始终返回父对象而不是bar对象。

如何确保byId如果它通过它调用,它将返回继承类的对象吗?

1 个答案:

答案 0 :(得分:1)

使用return new static($id);代替return new self($id);