PHP Conference Fukuoka 2025

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::setStaticPropertyValue设置 public static 属性的值

说明

public ReflectionClass::setStaticPropertyValue(string $name, mixed $value): void

设置 public 静态属性的值。如果属性是 private 或 protected,则方法会失败。

ReflectionProperty::setValue() 允许设置 public、private 和 protected 属性的值。

参数

name

属性的名称。

value

属性的值。

返回值

没有返回值。

更新日志

版本 说明
7.4.0 使用 ReflectionClass::setStaticPropertyValue() 设置 private 或 protected 静态属性现在会导致致命错误。之前会抛出 ReflectionException

参见

添加备注

用户贡献的备注 2 notes

up
19
Andrew Jackson
11 years ago
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 message 'Class test does not have a property named privateProperty'If you retrieve the method using the reflection class getProperty method you can circumnavigate this issue$reflectedProperty = $reflectedClass->getProperty('privateProperty');$reflectedProperty->setAccessible(true);$reflectedProperty = $reflectedProperty->setValue('bar');test::printProperties(); will echofoobar
up
10
chuck at manchuck dot com
13 years ago
It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.
To Top