为什么不能从 PHP 中的抽象类调用抽象函数?
我已经设置了一个抽象父类和一个扩展它的具体类。为什么父类不能调用抽象函数?
//foo.php
<?php
abstract class AbstractFoo{
abstract public static function foo();
public static function getFoo(){
return self::foo();//line 5
}
}
class ConcreteFoo extends AbstractFoo{
public static function foo(){
return "bar";
}
}
echo ConcreteFoo::getFoo();
?>
错误:
致命错误:无法在第 5 行的 foo.php 中调用抽象方法 AbstractFoo::foo()
I've set up an abstract parent class, and a concrete class which extends it. Why can the parent class not call the abstract function?
//foo.php
<?php
abstract class AbstractFoo{
abstract public static function foo();
public static function getFoo(){
return self::foo();//line 5
}
}
class ConcreteFoo extends AbstractFoo{
public static function foo(){
return "bar";
}
}
echo ConcreteFoo::getFoo();
?>
Error:
Fatal error: Cannot call abstract method AbstractFoo::foo() in foo.php on line 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个正确的实现;您应该使用 static 而不是 self,以便使用 后期静态绑定:
给出预期的“栏”。
请注意,这并不是真正的多态性。静态关键工作只是解析到调用静态方法的类中。如果声明抽象静态方法,您将收到严格警告。如果子(子)类中不存在,PHP 只会从父(超)类中复制所有静态方法。
This is a correct implementation; you should use static, not self, in order to use late static bindings:
gives the expected "bar".
Note that this is not really polymorphism. The static keywork is just resolved into the class from which the static method was called. If you declare an abstract static method, you will receive a strict warning. PHP just copies all static methods from the parent (super) class if they do not exist in the child (sub) class.
你注意到
self
这个词了吗?那是指向AbstractClass。因此它调用的是 AbstractClass::foo(),而不是 ConcreteClass::foo();
我相信 PHP 5.3 将提供后期静态绑定,但如果您不是该版本, self 将不会引用扩展类,而是引用该函数所在的类。
请参阅: http://us.php.net/manual/en/function.get- Called-class.php
You notice that word
self
?That is pointing to AbstractClass. Thus it is calling AbstractClass::foo(), not ConcreteClass::foo();
I believe PHP 5.3 will provide late static bindings, but if you are not on that version, self will not refer to an extended class, but the class that the function is located in.
See: http://us.php.net/manual/en/function.get-called-class.php
规则是
abstract
和static
关键字不能同时用于一个方法。带有
abstract
关键字的方法意味着子类必须实现它。将 static 添加到类的方法中允许我们使用该方法而无需实例化它。这就是错误发生的原因。
It's a rule that
abstract
andstatic
keywords can not be use on a method at the same time.A method with an
abstract
keyword means that sub-class must implement it. Adding static to a method of a class allows us to use the method without instantiating it.So that is why the error occurs.