I'm changing the accessible flag of my reflection class, this way:
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);
}
}
But when I try to set firstDate
property value, I'm getting the exception:
ReflectionException : Cannot access non-public member Me\Project\Class::firstDate.
Here is the source of the exception (setValue()
method):
$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;
}
Ok, found the problem. It seems that getProperty
returns a new instance every time you call it. So forgot changeAccessibility
method, you should do something like:
protected function getSubscriptionPeriod(\ReflectionClass $reflection)
{
$period = $reflection->newInstance();
$firstDateProperty = $reflection->getProperty('firstDate');
$firstDateProperty->setAccessible(true);
$firstDateProperty->setValue($period, 'foo');
return $period;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With