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 設定中,父類別負責設定模型子類別實例的屬性。