我正在改变我的反射类的可访问标志,这样:
protected function getBaseSubscriptionPeriodReflection()
{
$reflection = new \ReflectionClass('Me\Project\Class');
// Make all private and protected properties accessible
$this->changeAccessibility($reflection, true);
return $reflection;
}
protected function changeAccessibility(\ReflectionClass $reflection, $accessible)
{
$properties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE
| \ReflectionProperty::IS_PROTECTED);
foreach($properties as $property) {
$property->setAccessible($accessible);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试设置firstDate属性值时,我得到了异常:
ReflectionException:无法访问非公共成员Me\Project\Class :: firstDate.
这是异常的来源(setValue()方法):
$reflection = $this->getBaseSubscriptionPeriodReflection();
$this->getSubscriptionPeriod($reflection)
protected function getSubscriptionPeriod(\ReflectionClass $reflection)
{
$period = $reflection->newInstance();
// Reflection exception here
$reflection->getProperty('firstDate')->setValue($period, 'foo');
return $period;
}
Run Code Online (Sandbox Code Playgroud)
gre*_*emo 12
好的,发现了问题.似乎getProperty每次调用它都会返回一个新实例.所以忘了changeAccessibility方法,你应该做的事情如下:
protected function getSubscriptionPeriod(\ReflectionClass $reflection)
{
$period = $reflection->newInstance();
$firstDateProperty = $reflection->getProperty('firstDate');
$firstDateProperty->setAccessible(true);
$firstDateProperty->setValue($period, 'foo');
return $period;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3043 次 |
| 最近记录: |