我正在尝试对类的静态属性执行备份/恢复功能。我可以使用反射对象的getStaticProperties()
方法获得所有静态属性及其值的列表。这将获取private
和public static
属性及其值。
问题是,当我尝试使用反射对象setStaticPropertyValue($key, $value)
方法恢复属性时,似乎没有得到相同的结果。与getStaticProperties()
一样,private
和protected
变量对此方法不可见。看起来并不一致。
有没有办法使用反射类来设置私有/受保护的静态属性,或者其他方式?
尝试了
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();
https://stackoverflow.com/questions/6448551
复制相似问题