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条)

报告相同问题?