PHP Conference Japan 2024

ReflectionProperty::setValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::setValue設定屬性值

說明

public ReflectionProperty::setValue(物件 $object, 混合 $value): void
public ReflectionProperty::setValue(混合 $value): void

設定(更改)屬性的值。

注意事項自 PHP 8.3.0 起,不建議以單一參數呼叫此方法,請改用 ReflectionClass::setStaticPropertyValue()

參數

object(物件)

如果屬性是非靜態的,則必須提供一個物件來更改其屬性。如果屬性是靜態的,則*必須*提供 null 值。

value(值)

新的值。

回傳值

無回傳值。

更新日誌

版本 說明
8.3.0 不建議以單一參數呼叫此方法,請改用 ReflectionClass::setStaticPropertyValue() 來修改靜態屬性。
8.1.0 現在可以直接使用 ReflectionProperty::setValue() 讀取私有和受保護的屬性。先前,需要透過呼叫 ReflectionProperty::setAccessible() 使它們可被讀取;否則會拋出 ReflectionException

範例

範例 #1 ReflectionProperty::setValue() 範例

<?php
class Foo {
public static
$staticProperty;

public
$property;
protected
$privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

// 從 PHP 8.3 開始,不應再使用 setValue 設定靜態屬性值,請改用 setStaticPropertyValue()
$reflectionClass->setStaticPropertyValue('staticProperty', 'foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true); // 僅在 PHP 8.1.0 之前需要
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

以上範例將輸出

string(3) "foo"
string(3) "bar"
string(6) "foobar"

另請參閱

新增註解

使用者貢獻的註解 3 則註解

me at ircmaxell dot om
13 年前
您可以使用 ReflectionProperty::setValue 來設定靜態屬性和一般實例屬性的值。只需傳遞 null 作為實例即可。

<?php
Foo {
protected static
$bar = null;
public static function
sayBar() {
echo
self::$bar;
}
}

$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');

Foo::sayBar(); // 顯示 "foo"
?>
p stewart imperial ac uk
1 年前
setValue 方法可以用於唯讀屬性,但前提是該屬性尚未被初始化。

<?php

類別 Person
{
private readonly
int $age;
public function
__construct(array $props = []) {
if (isset(
$props['age'])) {
$this->age = (int)$props['age'];
}
}
}

$personWithKnownAge = new Person(['age' => 50]);

$reflection = new ReflectionProperty($personWithKnownAge, 'age');
$reflection->setValue($personWithKnownAge, 10); // 失敗 - 年齡已經初始化,值無法更改。

$personWithUnknownAge = new Person();

$reflection = new ReflectionProperty($personWithUnknownAge, 'age');
$reflection->setValue($personWithUnknownAge, 10); // 成功 - 年齡尚未初始化,可以設定值。
?>

這在需要從定義類別外部初始化屬性的情況下很有用,例如在 ORM 設定中,父類別負責設定模型子類別實例的屬性。
temirkhan.nasukhov
2 年前
請記住,setValue 無法用於唯讀屬性。

<?php

類別 Person
{
public function
__construct(private readonly int $age) {}
}

$someOldPerson = new Person(80);

$reflection = new ReflectionProperty($someOldPerson, 'age');
$reflection->setValue($someOldPerson, 10); // 致命錯誤:未捕捉錯誤:無法修改唯讀屬性 Person::$age
To Top