vendredi 18 mars 2022

How do I change a readonly property using reflection in PHP 8.1?

Is there any way, using reflection or otherwise, to change a readonly property that has already been set?

We sometimes do that in tests, and we don't want to avoid using readonly props just for testing purposes.

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




Aucun commentaire:

Enregistrer un commentaire