PHP 可以做相当简单的继承事情吗?
我有以下代码:
abstract class AbstractParent {
function __construct($param) { print_r($param); }
public static function test() { return new self(1234); }
}
class SpecificClass extends AbstractParent {}
当我调用 SpecificClass::test()
时,我收到错误:
Fatal error: Cannot instantiate abstract class AbstractParent
所以我基本上想要的只是让 AbstractParent
的 test()
实例化调用此 test()
的类(因此,在我的示例中,实例化 SpecificClass
)。
I have the following code:
abstract class AbstractParent {
function __construct($param) { print_r($param); }
public static function test() { return new self(1234); }
}
class SpecificClass extends AbstractParent {}
When I invoke SpecificClass::test()
, I am getting an error:
Fatal error: Cannot instantiate abstract class AbstractParent
So what I basically want is just to let AbstractParent
's test()
instantiate class where this test()
was called from (so, in my example, instantiate SpecificClass
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
之前版本 5.3 仅具有以下解决方法:
Prior version 5.3 Only with the following work around:
您可以在 PHP 5.3 中执行此操作,该版本仍处于 alpha 版本。 您正在寻找的称为“后期静态绑定”。 您希望父类在静态方法中引用子类。 你还不能做到这一点,但它即将到来......
编辑:你可以在这里找到更多信息 - http://www.php.net/manual/en/language.oop5.late-static-bindings.php
You can do it in PHP 5.3, which is still in alpha. What you're looking for is called Late-Static-Binding. You want the parent class to refer to the child class in a static method. You can't do it yet, but it's coming...
Edit: You can find more info here - http://www.php.net/manual/en/language.oop5.late-static-bindings.php