我正在以这种方式更改反射类的可访问标志:
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);
}
}
但是当我尝试设置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;
}