[英]How do I change a readonly property using reflection in PHP 8.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
属性的唯一方法是在不调用其构造函数的情况下反映 object。 但是,不确定它是否对您的特定情况有用
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
注意:我们实际上并没有“改变”我们只是第一次设置它的属性,因为没有调用构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.