ReflectionException“无法访问非公共成员”,但属性是否可访问?

时间:2012-12-14 13:30:49

标签: php reflection

我正在改变我的反射类的可访问标志,这样:

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:无法访问非公共成员   我\项目\类:: 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;
}

1 个答案:

答案 0 :(得分:11)

好的,发现了问题。似乎getProperty每次调用它时都会返回一个新实例。所以忘了changeAccessibility方法,你应该做类似的事情:

protected function getSubscriptionPeriod(\ReflectionClass $reflection)
{
    $period = $reflection->newInstance();

    $firstDateProperty = $reflection->getProperty('firstDate');
    $firstDateProperty->setAccessible(true);
    $firstDateProperty->setValue($period, 'foo');

    return $period;
}