Is there a way to set a private / protected static property using reflection classes?

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

The problem is that I do not get the same result when I try to restore properties using the reflection object methods setStaticPropertyValue($key, $value) . private and protected variables are not visible to this method, as they relate to getStaticProperties() . Seems inconsistent.

Is it possible to set the static property private / protected using reflection classes or in any other way?

TESTED

 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(); 
+49
visibility reflection php
Jun 23 '11 at 2:01
source share
2 answers

To access the private / protected properties of a class, we may need to first establish the accessibility of this class 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'); 
+63
Jun 23 '11 at 2:11
source share

To access the private / protected properties of a class using reflection, without the need for an instance of ReflectionObject :

For static properties:

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


For non-static properties:

 <?php $instance = New SomeClassName(); $reflection = new \ReflectionProperty(get_class($instance), 'propertyName'); $reflection->setAccessible(true); $reflection->setValue($instance, 'new property value'); 
+31
Nov 07 '12 at 18:03
source share



All Articles