【问题标题】:Creating a new instance of an inherited class through the inherited static methods通过继承的静态方法创建继承类的新实例
【发布时间】:2018-05-10 12:32:35
【问题描述】:

我的班级中有一个方法可以在执行时创建一个新的“自我”。

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 将返回如果通过它调用继承类的对象?

【问题讨论】:

  • test() 怎么会打电话给foo::byId()?什么..
  • Lawrence Cherone 我不确定你的意思,我希望能够通过使用静态 bar::byId( id ) 调用 bar->test() ,其中 byId 静态方法是从 foo 继承的
  • 你试过用return new static($id);代替return new self($id);吗?
  • 哦,对了,@PhilippMaurer 已经对它进行了排序;p
  • New self vs. new static的可能重复

标签: php inheritance


【解决方案1】:

使用return new static($id); 而不是return new self($id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多