有什么方法可以使用反射类来设置私有/受保护的静态属性? [英] Is there any way to set a private/protected static property using reflection classes?

查看:188
本文介绍了有什么方法可以使用反射类来设置私有/受保护的静态属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to perform a backup/restore function for static properties of classes. I can get a list of all of the static properties and their values using the reflection objects getStaticProperties() method. This gets both private and public static properties and their values.

问题是,当尝试使用反射对象setStaticPropertyValue($key, $value)方法还原属性时,我似乎没有得到相同的结果. privateprotected变量与getStaticProperties()一样,在此方法中不可见.似乎不一致.

The problem is I do not seem to get the same result when trying to restore the properties with the reflection objects setStaticPropertyValue($key, $value) method. private and protected variables are not visible to this method as they are to getStaticProperties(). Seems inconsistent.

是否有使用反射类来设置私有/受保护的静态属性的方法,或者其他任何方式?

Is there any way to set a private/protected static property using reflection classes, or any other way for that matter?

尝试

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();

推荐答案

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

For accessing private/protected properties of a class we may need to set the accessibility of that class first, using reflection. Try the following code:

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

这篇关于有什么方法可以使用反射类来设置私有/受保护的静态属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆