note 128981 added to reflectionclass.newinstancewithoutconstructor

From: Date: Sat, 28 Oct 2023 20:04:38 +0000
Subject: note 128981 added to reflectionclass.newinstancewithoutconstructor
Groups: php.notes 
Request: Send a blank email to php-notes+get-220938@lists.php.net to get a copy of this message
Using ReflectionClass::newInstanceWithoutConstructor and ReflectionProperty::setValue allow to set a value for a readonly promoted property. For example this code works (tested on PHP 8.2) : <?php class Test { public function __construct(public readonly string $name) {} } $test1 = new Test('test1'); $reflectionProperty = new ReflectionProperty(Test::class, 'name'); // next line would throw a Fatal error $reflectionProperty->setValue($test1, 'error'); $reflectionClass = new ReflectionClass(Test::class); $test2 = $reflectionClass->newInstanceWithoutConstructor(); $reflectionProperty->setValue($test2, 'test2'); echo $test2->name; // will output "test2" ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 2a01:e0a:aca:4700:154d:7d64:a1ff:d062) ---- Manual Page -- https://php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php Edit -- https://main.php.net/note/edit/128981 Del: integrated -- https://main.php.net/note/delete/128981/integrated Del: useless -- https://main.php.net/note/delete/128981/useless Del: bad code -- https://main.php.net/note/delete/128981/bad+code Del: spam -- https://main.php.net/note/delete/128981/spam Del: non-english -- https://main.php.net/note/delete/128981/non-english Del: in docs -- https://main.php.net/note/delete/128981/in+docs Del: other reasons-- https://main.php.net/note/delete/128981 Reject -- https://main.php.net/note/reject/128981 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220938) next »