有什么办法来设置私人/受保护的静态属性使用reflection类?

我正在尝试执行类的静态属性的备份/恢复function。 我可以使用reflection对象getStaticProperties()方法获取所有静态属性及其值的列表。 这将获得privatepublic static属性及其值。

问题是我试图用reflection对象setStaticPropertyValue($key, $value)方法恢复属性时似乎并没有得到相同的结果。 privateprotectedvariables对于这个方法是不可见的,因为它们是getStaticProperties() 。 似乎不一致。

有什么办法设置私人/受保护的静态属性使用reflection类,或任何其他方式呢?

受审

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

为了访问一个类的私有/受保护的属性,我们可能需要首先使用reflection来设置该类的可访问性。 试试下面的代码:

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

为了访问一个类的私有/受保护的属性,使用reflection,而不需要一个ReflectionObject实例:

对于静态属性:

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

对于非静态属性:

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