5

我正在以这种方式更改反射类的可访问标志:

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;
}
4

1 回答 1

15

好的,找到问题了。似乎getProperty每次调用它都会返回一个新实例。所以忘记了changeAccessibility方法,你应该这样做:

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

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

    return $period;
}
于 2012-12-14T13:43:46.287 回答