假设你有一个像这样声明的类:
class DummyObject{
public $attr;
public function __construct(){
$this->attr=array('val_1','val_2','val_3');
}
}
Run Code Online (Sandbox Code Playgroud)
这样做:
$obj=(new DummyObject1());
$attr=&$obj->attr;
Run Code Online (Sandbox Code Playgroud)
您将获得一个引用,$attr因此在DummyObject $ obj实例中也将对数组进行任何修改.
而现在,最后的问题.使用反射,¿我怎样才能获得对存储的数组的引用$attr而不是副本?我试过这个没有成功:
$obj=(new DummyObject());
$reflector = new ReflectionObject($obj);
$reflectorProperty = $reflector->getProperty('attr');
$propertyValue=$reflectorProperty->getValue($ref);
Run Code Online (Sandbox Code Playgroud)
实际上,$attr是原始数组的副本.
提前致谢!
从PHP 5.4开始,你可以不用反思地做到这一点:
class Kitchen
{
private $yummy = 'cake';
}
$reader = function & ($object, $property) {
$value = & Closure::bind(function & () use ($property) {
return $this->$property;
}, $object, $object)->__invoke();
return $value;
};
$kitchen = new Kitchen();
$cake = & $reader($kitchen, 'yummy');
$cake = 'sorry, I ate it!';
var_dump($kitchen);
Run Code Online (Sandbox Code Playgroud)
这要归功于PHP 5.4在运行时切换闭包范围的能力.
您可以在http://3v4l.org/sZMt1找到一个正在运行的示例
我实际上在http://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/详细解释了技术和最终用例.