我在运行时创建了一个对象。它有一个protected属性,该属性也是在运行时创建的对象。这个属性对象有一个字符串类型的受保护属性,我需要获取它的值。
<?php
class A
{
// will be set at runtime
protected $s = 'hello';
}
class B
{
// will be set at runtime
protected $a;
public function setA(A $a)
{
$this->a = $a;
}
}
// for example, somewhere in the library
$a = new A();
$b = new B();
$b->setA($a);
// I have $b returned from some library method call
$r = new ReflectionObject($b);
// How to get 'hello'?
关于反射的文档是相当稀疏的,有人可以帮助我这里吗?
// for example
$a = new A();
$b = new B();
$b->setA($a);
$r = new ReflectionClass($b);
$property = $r->getProperty("a");
$property->setAccessible(true);
$a = $property->getValue($b);
$r = new ReflectionClass($a);
$property = $r->getProperty("s");
$property->setAccessible(true);
$s = $property->getValue($a);
有点棘手,甚至不确定是否需要,但它现在工作了