gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:04:11 24 4
gpt4 key购买 nike

我想重新定义一个方法,并调用我祖先的版本,而不是我 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com