php - ReflectionException "Cannot access non-public member",但属性可访问?

标签 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 : 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/

相关文章:

php - 在 mysql 插入之前清理数组值

php - 我可以使用不是磁盘上文件的证书来使用 SSL 套接字吗? (即在数据库中)

php - 没有用户界面的 gmail-api php

php - Elasticsearch作为 session 数据存储?

java - 属性访问异常 : could not get a field value by reflection getter While using Hibernate

java - Netbeans 7.2.1,Java 反射,method.invoke(super, ..)

c# - 根据单元格值过滤datagridview中的对象列表

php - 使用 PDO 获取上一行以创建链接

java - 从 Spring 上下文访问 Spring 测试类对象

c# - 在运行时在 C# 中加载 DLL