使用 ReflectionClass::newInstanceWithoutConstructor 和 ReflectionProperty::setValue 可以为只读提升属性设置值。例如,以下代码有效(在 PHP 8.2 上测试)
<?php
class Test
{
public function __construct(public readonly string $name)
{}
}
$test1 = new Test('test1');
$reflectionProperty = new ReflectionProperty(Test::class, 'name');
$reflectionProperty->setValue($test1, 'error');
$reflectionClass = new ReflectionClass(Test::class);
$test2 = $reflectionClass->newInstanceWithoutConstructor();
$reflectionProperty->setValue($test2, 'test2');
echo $test2->name;