为什么不能从 PHP 中的抽象类调用抽象函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2859633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't you call abstract functions from abstract classes in PHP?
提问by Cam
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.phpon line 5
致命错误:无法 在第 5 行的foo.php 中调用抽象方法 AbstractFoo::foo()
回答by Artefacto
This is a correct implementation; you should use static, not self, in order to use late static bindings:
这是一个正确的实现;为了使用后期静态绑定,您应该使用静态而不是自我:
abstract class AbstractFoo{
public static function foo() {
throw new RuntimeException("Unimplemented");
}
public static function getFoo(){
return static::foo();
}
}
class ConcreteFoo extends AbstractFoo{
public static function foo(){
return "bar";
}
}
echo ConcreteFoo::getFoo();
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.
请注意,这并不是真正的多态性。静态键工作只是解析为调用静态方法的类。如果声明抽象静态方法,则会收到严格警告。如果子(子)类中不存在父类(超级)类中的所有静态方法,PHP 只会复制它们。
回答by Tyler Carter
You notice that word self?
你注意到那个词了self吗?
That is pointing to AbstractClass. Thus it is calling AbstractClass::foo(), not ConcreteClass::foo();
那就是指向 AbstractClass。因此它调用的是 AbstractClass::foo(),而不是 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.
我相信 PHP 5.3 将提供后期静态绑定,但如果您不在该版本上,则 self 不会引用扩展类,而是指函数所在的类。
See: http://us.php.net/manual/en/function.get-called-class.php
见:http: //us.php.net/manual/en/function.get-called-class.php
回答by Tomheng
It's a rule that abstractand statickeywords can not be use on a method at the same time.
abstract和static关键字不能同时用于一个方法是一个规则。
A method with an abstractkeyword means that sub-class must implement it. Adding static to a method of a class allows us to use the method without instantiating it.
带有abstract关键字的方法意味着子类必须实现它。向类的方法添加静态允许我们在不实例化它的情况下使用该方法。
So that is why the error occurs.
所以这就是错误发生的原因。

