php - 在 php 类之外使用父级
问题描述
给定
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 类上使用可调用对象并将其绑定到 B 类的对象,或者使用父类,但这些方法似乎都没有帮助。
解决方案
在 PHP 中,您可以使用反射(内省或元编程)来做到这一点,就像类/对象设计一样,封装通常会禁止它。
鉴于有问题的类定义中的以下内容:
$b = new B();
$b->test;
它通过使用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"
推荐阅读
- html - 阻止调整图像大小
- ruby-on-rails - 方法与?名义上不会在权威政策中引发方法错误
- c++ - 如何找到传递给函数的矩阵的大小?
- javascript - 为字符串添加前缀 +1
- android - 字体样式没有改变android中的数字
- ionic-framework - Ionic 4 页面动画
- android - 找不到 com.wix:detox:+ 的任何匹配项
- reactjs - 使用 Twitter Apollo GraphQL 登录
- sql - 如果添加了 WHERE 子句,LEFT JOIN 不返回任何结果?
- python - django OSError:在 Windows 上找不到名为“cairo”的库