【发布时间】: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
标签: php inheritance