我想重新定义一个方法,并调用我祖先的版本,而不是我 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
,有效地只执行 A
的 foo()
和 C
的 foo()
。因此,让我们进入反射并获取 A
的 foo()
方法,并在 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/