setValue 可用于只读属性,但前提是该属性尚未初始化
<?php
class 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 设置,其中父类负责设置模型子类实例的属性。