有没有办法使用反射类设置私有/受保护的静态属性?

dqh*_*cks 58 php reflection visibility

我正在尝试为类的静态属性执行备份/恢复功能.我可以使用反射对象getStaticProperties()方法获取所有静态属性及其值的列表.这得到两个privatepublic static属性及其值.

问题是我尝试使用反射对象setStaticPropertyValue($key, $value)方法恢复属性时似乎没有得到相同的结果.private并且protected变量对于此方法不可见getStaticProperties().似乎不一致.

有没有办法使用反射类或任何其他方式设置私有/受保护的静态属性?

受审

class Foo {
    static public $test1 = 1;
    static protected $test2 = 2;

    public function test () {
        echo self::$test1 . '<br>';
        echo self::$test2 . '<br><br>';
    }

    public function change () {
        self::$test1 = 3;
        self::$test2 = 4;
    }
}

$test = new foo();
$test->test();

// Backup
$test2 = new ReflectionObject($test);
$backup = $test2->getStaticProperties();

$test->change();

// Restore
foreach ($backup as $key => $value) {
    $property = $test2->getProperty($key);
    $property->setAccessible(true);
    $test2->setStaticPropertyValue($key, $value);
}

$test->test();
Run Code Online (Sandbox Code Playgroud)

Sha*_*eer 76

要访问类的私有/受保护属性,我们可能需要首先使用反射设置该类的可访问性.请尝试以下代码:

$obj         = new ClassName();
$refObject   = new ReflectionObject( $obj );
$refProperty = $refObject->getProperty( 'property' );
$refProperty->setAccessible( true );
$refProperty->setValue(null, 'new value');
Run Code Online (Sandbox Code Playgroud)

  • 请注意,只有在设置的属性是*static*属性时,才允许使用` - > setValue(null,'...')`.如果你试图修改一个对象属性,你需要提供一个真实的实例,或者PHP会抱怨`ReflectionProperty :: setValue()期望参数1是对象,null给定`. (12认同)

Mih*_* H. 38

要访问类的私有/受保护属性,请使用反射,而不需要ReflectionObject实例:

对于静态属性:

<?php
$reflection = new \ReflectionProperty('ClassName', 'propertyName');
$reflection->setAccessible(true);
$reflection->setValue(null, 'new property value');
Run Code Online (Sandbox Code Playgroud)


对于非静态属性:

<?php
$instance = New SomeClassName();
$reflection = new \ReflectionProperty(get_class($instance), 'propertyName');
$reflection->setAccessible(true);
$reflection->setValue($instance, 'new property value');
Run Code Online (Sandbox Code Playgroud)