PHPeste 2025 - Parnaiba-PI

ReflectionClass::setStaticPropertyValue

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

ReflectionClass::setStaticPropertyValuepublicなstaticプロパティの値を設定する

説明

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

publicなstaticプロパティの値を設定します。 プロパティがprivateやprotectedだった場合は、 このメソッドは失敗します。

ReflectionProperty::setValue() を使うと、 public, private, protected なプロパティの値を設定できます。

パラメータ

name

プロパティの名前。

value

新しいプロパティの値。

戻り値

値を返しません。

変更履歴

バージョン 説明
7.4.0 ReflectionClass::setStaticPropertyValue() を private や protected なプロパティに対して使うと、 致命的なエラーが発生するようになりました。 これより前のバージョンでは、 ReflectionException がスローされていました。

参考

add a note

User Contributed Notes 2 notes

up
25
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 echo
foo
bar
up
15
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