setValue can be used for readonly properties, but only if the property has not yet been initialised:
<?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); ?>
This can be useful for situations where it is desirable to initialise properties from outside of the defining class, for example an ORM setup where the parent class is responsible for setting properties on a model subclass instance.