繁体   English   中英

如何在 PHP 8.1 中使用反射更改只读属性?

[英]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

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

注意:我们实际上并没有“改变”我们只是第一次设置它的属性,因为没有调用构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM