【问题标题】:How to skip execution of a parent method to execute grandparent method? [duplicate]如何跳过执行父方法来执行祖父方法? [复制]
【发布时间】:2012-09-17 08:16:22
【问题描述】:

可能重复:
How do I get a PHP class constructor to call its parent's parent's constructor

我知道这听起来很奇怪,但我正在尝试解决一个错误。如何调用祖父方法?

<?php
class Person {
    function speak(){ echo 'person'; }
}
class Child extends Person {
    function speak(){ echo 'child'; }
}
class GrandChild extends Child {
    function speak(){
      //skip parent, in order to call grandparent speak method
    }
}

【问题讨论】:

  • 您是否可以控制层次结构中的所有类?

标签: php


【解决方案1】:

你可以直接调用它;

class GrandChild extends Child {
    function speak() {
       Person::speak();
    }
}

parent 只是一种使用最接近的基类的方法,而无需在多个地方使用基类名称,但提供任何基类的类名称同样可以使用它而不是直接父类。

【讨论】:

    【解决方案2】:

    PHP 有本地方式来做到这一点。

    试试这个:

    class Person {
    
        function speak(){ 
    
            echo 'person'; 
        }
    }
    
    class Child extends Person {
    
        function speak(){
    
            echo 'child';
        }
    }
    
    class GrandChild extends Child {
    
        function speak() {
    
             // Now here php allow you to call a parents method using this way.
             // This is not a bug. I know it would make you think on a static methid, but 
             // notice that the function speak in the class Person is not a static function.
    
             Person::speak();
    
        }
    }
    
    $grandchild_object = new GrandChild();
    
    $grandchild_object->speak();
    

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多