Is there any way to set a private/protected static property using reflection classes?
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');
For accessing private/protected properties of a class, using reflection, without the need for a ReflectionObject
instance:
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');