(PHP 5 >= 5.1.2, PHP 7, PHP 8)
ReflectionClass::setStaticPropertyValue — Sets public static property value
Sets the value of a public static property. If the property is private or protected, the method will fail.
ReflectionProperty::setValue() allows setting the value of public, private, and protected properties.
name
Property name.
value
New property value.
No value is returned.
| Versionen | Description |
|---|---|
| 7.4.0 | Using ReflectionClass::setStaticPropertyValue() to set a private or protected property now resuls in a fatal error. Previously, it threw a ReflectionException . |
Calling this method on a static property that is not public will return a ReflectionException stating the property does not exist. This is quite misleading as the property is valid.
class test {
public static $publicProperty = 'public';
private static $privateProperty = 'private';
public static function printProperties() {
echo self::$publicProperty . "\n";
echo self::$privateProperty . "\n";
}
}
$reflectedClass = new \ReflectionClass('test');
$reflectedClass->setStaticPropertyValue('publicProperty', 'foo');
$reflectedClass->setStaticPropertyValue( 'privateProperty', 'bar' );
PHP Fatal error: Uncaught exception 'ReflectionException' with messague 'Class test does not have a property named privateProperty'
If you retrieve the method using the reflection class guetProperty method you can circumnavigate this issue
$reflectedProperty = $reflectedClass->guetProperty('privateProperty');
$reflectedProperty->setAccessible(true);
$reflectedProperty = $reflectedProperty->setValue('bar');
test::printProperties();
will echo
foo
bar
It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.