PHP - 重新定义方法并调用相同方法的祖先版本

标签 php inheritance

我想重新定义一个方法,并调用我祖先的版本,而不是我 parent 的。

这是一个简短的例子:

// This class is autogenerated and I am not supposed to modify it.
class myParent extends myGrandparent {

  function doSomething() {
    doA();
    doB();
    doC();
    parent::doSomething();
  }

}

// Here is my code
class myClass extends myParent {

  function doSomething() {
    // doA();    // I don't want to do A anymore.
    // doB();    // Neither B.
    doC();       // But I want to keep doing C.
    parent::doSomething();      // OOPS!!  This does A and B (and C again)!
  }

}

如何直接调用 myGrandparent 的方法,而不是 myParent 的方法?

最佳答案

我不同意“你不能这样做”的论点——你可以Reflection做到这一点.

考虑以下类结构:

class A { 
    function foo() { 
        echo 'A'; 
    }
}

class B extends A { 
    function foo() { 
        parent::foo();  
        echo 'B'; 
    }
}

class C extends B { 
    function foo() { 
        parent::foo();
        echo 'C'; 
    }
}

初始化时:

$o = new C;
$o->foo();

将打印(如预期,见 this demo ):

ABC

挑战在于从输出中移除 B,有效地只执行 Afoo()Cfoo()。因此,让我们进入反射并获取 Afoo() 方法,并在 C 的对象上调用它。现在考虑 C 的替代定义:

class C extends B { 
    function foo() { 
        $ref = new ReflectionClass( $this);
        $parent = $ref->getParentClass()->getParentClass();
        $parent->getMethod( 'foo')->invoke( $this);
        echo 'C'; 
    }
}

现在,您只会得到输出(如 this demo 中所示):

AC

这是否是“良好做法”取决于 OP。我想我已经证明可以“跳过”B 函数的实现并从孙类调用祖父函数。

关于PHP - 重新定义方法并调用相同方法的祖先版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12286960/

相关文章:

php - CSS 编辑两个导航栏(Adelle 主题)

java - 在Java中,我可以将子类 "based on"的实例作为父类(super class)的实例吗?

java - 代码返回节点而不是子类的值

Scala:如何设置在抽象父类(super class)构造函数中定义的实例字段?

c++ - 错误:没有匹配函数来调用 second::second,候选者是:second::second(

php - 电子邮件验证的标准方法是什么

php - 在段落中显示 mysql 内容时出现问题

php - 需要帮助寻找 gedit 的 HTML、CSS、PHP 代码格式化程序

url-rewriting - nginx 没有将重写传递给 php

php - 覆盖类常量与属性