php – “Class X扩展Y(抽象),Y实现Z(接口). “不能调用接口Z的
发布时间:2020-12-13 21:55:09 所属栏目:PHP教程 来源:网络整理
导读:这是我的 PHP抽象类.最底层的类是扩展抽象类并将一些复杂的计算逻辑留给父实现的类之一. 接口类(最顶层的抽象)的要点是强制那些较低的实现具有自己的静态公共函数id($params = false){方法. // My top level abstraction,to be implemented only by "MyAbstr
这是我的
PHP抽象类.最底层的类是扩展抽象类并将一些复杂的计算逻辑留给父实现的类之一.
接口类(最顶层的抽象)的要点是强制那些较低的实现具有自己的静态公共函数id($params = false){方法. // My top level abstraction,to be implemented only by "MyAbstraction" interface MyInterface{ static public function id(); } // My second (lower) level of abstraction,to be extended // by all child classes. This is an abstraction of just the // common heavy lifting logic,common methods and properties. // This class is never instantiated,hence the "abstract" modifier. // Also,this class doesn't override the id() method. It is left // for the descendant classes to do. abstract class MyAbstraction implements MyInterface{ // Some heavy lifting here,including common methods,properties,etc // .... // .... static public function run(){ $this->id = self::id(); // This is failing with fatal error } } // This is one of many "children" that only extend the needed methods/properties class MyImplementation extends MyAbstraction{ // As you can see,I have implemented the "forced" // method,coming from the top most interface abstraction static public function id(){ return 'XXX'; } } 最终的结果是,如果我打电话: $o = new MyImplementation(); $o->run(); 我收到一个致命的错误: 为什么MyAbstraction :: run()调用其父(接口)的id()方法而不是在其子(后代)类中找到的方法? 解决方法
>接口中声明的所有方法都必须是公共的;这是界面的本质.
Reference – PHP interface
>您在MyAbstraction类中使用self :: id(),self始终引用相同的类. reference self vs static 你应该使用静态而不是自我.请参阅以下代码. interface MyInterface{ public function id(); } abstract class MyAbstraction implements MyInterface{ public $id; // Some heavy lifting here,etc // .... // .... public function run(){ $this->id = static::id(); // This is failing with fatal error } } class MyImplementation extends MyAbstraction{ // As you can see,I have implemented the "forced" // method,coming from the top most interface abstraction public function id(){ return 'XXX'; } } $o = new MyImplementation(); $o->run(); 在上面的代码中,static :: id()将调用上下文中的类函数,即MyImplementation类. 这种现象称为Late Static Binding (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |