首页 > 解决方案 > 在 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 类的对象,或者使用父类,但这些方法似乎都没有帮助。

标签: phpinheritance

解决方案


在 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"

推荐阅读