我正在以这种方式更改我的反射类的可访问标志:
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 : Cannot access non-public member 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;
}
最佳答案
好的,找到问题了。似乎每次调用 getProperty
都会返回一个新实例。所以忘记了 changeAccessibility
方法,你应该这样做:
protected function getSubscriptionPeriod(\ReflectionClass $reflection)
{
$period = $reflection->newInstance();
$firstDateProperty = $reflection->getProperty('firstDate');
$firstDateProperty->setAccessible(true);
$firstDateProperty->setValue($period, 'foo');
return $period;
}
关于php - ReflectionException "Cannot access non-public member",但属性可访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879626/