如何在PHP8.1中使用反射更改只读属性



是否有任何方法可以使用反射或其他方式更改已设置的只读属性?

我们有时会在测试中这样做,我们不想避免仅仅为了测试目的而使用只读道具。

class Acme {
public function __construct(
private readonly int $changeMe,
) {}
}
$object= new Acme(1);
$reflectionClass = new ReflectionClass($object);
$reflectionProperty = $reflectionClass->getProperty('changeMe');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, 2);
Fatal error: Uncaught Error: Cannot modify readonly property Acme::$changeMe

我能想到的更改readonly属性的唯一方法是在不调用其构造函数的情况下反映对象。然而,不确定它是否在您的特定情况下有用

class Acme {
public function __construct(
public readonly int $changeMe,
) {}
}
$object = new Acme(1);
$reflection = new ReflectionClass($object);
$instance = $reflection->newInstanceWithoutConstructor();
$reflectionProperty = $reflection->getProperty('changeMe');
$reflectionProperty->setValue($instance, 33);
var_dump($reflectionProperty->getValue($instance)); // 33

https://3v4l.org/mis1l#v8.1.0

注意:我们实际上并不是"改变";由于没有调用构造函数,因此我们只是第一次设置该属性。

最新更新