Voting

: min(four, four)?
(Example: nine)

The Note You're Voting On

benoit dot wery at online dot fr
1 year ago
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"

<< Back to user notes page

To Top