Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReflectionException "Cannot access non-public member", but property is accessible?

Tags:

php

reflection

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;
}
like image 242
gremo Avatar asked Dec 14 '12 13:12

gremo


1 Answers

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;
}
like image 161
gremo Avatar answered Nov 07 '22 06:11

gremo