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

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


You can implement also a class internal method to change the object properties access setting and then set value with $instanve->properyname = .....:

public function makeAllPropertiesPublic(): void{    $refClass = new ReflectionClass(\get_class($this));    $props = $refClass->getProperties();    foreach ($props as $property) {        $property->setAccessible(true);    }}