dongmi5015 2016-06-22 13:54
浏览 34
已采纳

PHP调用超级父方法

I'm not sure at all if there is such a term but here is what I want to do

class A {
    function a($a) {
        return $a;
    }
}

class B extends A {
    function a($a) {
        return parent::a('B' . $a);
    }
}

class C extends B {
    function a($a) {
        return superparent::a('C' . $a);
    }
}

$c = new C();
echo $c->a('C'); // "CC"

I want to bypass all medial classes and call the function on the parent where it was defined for the first time - is this possible?

  • 写回答

4条回答 默认 最新

  • dtnwm4807 2016-06-22 13:59
    关注

    No, and it's a terrible idea. All your class C knows is that it extends B. It cannot know nor should it know what, if anything, B extends. C cannot count on B extending anything, nor should it be aware of specific methods of that grand parent and their implementation details. You may be refactoring B tomorrow to extend another class, or to extend no class at all. Code would start breaking left and right if you established such three-class-crossover dependencies.

    Classes should only interact with peers they're directly associated with, either through inheritance or dependency injection.

    Just logically speaking: B adds something necessary to the behaviour of A to "make it a B", and C adds something to make it a C. C builds on B, so anything B does C should do as well. Having C "jump over" B back to A suggests that your logic and responsibility assignment is mixed up in your class hierarchy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?