gpt4 book ai didi

php - 在 php 类之外使用父级

转载 作者:行者123 更新时间:2023-12-04 13:08:09 25 4
gpt4 key购买 nike

给定

abstract class A {
public function __get($key) {
...
}
}

class B extends A {
public function __get($key) {
...
}
}

class C {
public function test($bObject) {
//Call the __get function of A on the object of B
}
}

我如何从 C::test 调用 B 的对象上的 A::__get?我已经研究过在类 A::__get 上使用可调用对象并将其绑定(bind)到类 B 的对象,或者使用父类,但这两种方法似乎都没有帮助。

最佳答案

在 PHP 中,您可以通过反射(内省(introspection)元编程)实现这一点,因为类/对象设计通常禁止封装.

根据所讨论的类定义给出以下内容:

$b = new B();
$b->test;

它通过获取 closure of the parents method 来工作使用 B 对象(例如,您问题中的 $bObject 或此处示例中的 $b ),然后调用它:

(new ReflectionObject($b))
->getParentClass()
->getMethod('__get')
->getClosure($b)('test'); // or: ->invoke($b, 'test');

演示:https://3v4l.org/0tj26以及 PHP 7.3.0 - 7.3.29、7.4.0 - 7.4.21、8.0.0 - 8.0.8 的输出:

string(8) "B::__get"
string(4) "test"
string(8) "A::__get"
string(4) "test"

关于php - 在 php 类之外使用父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68413123/

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