Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Init Readonly Properties In Child Class

Readonly properties used to be only assigned a value in their definition class. Even when they were protected, they could not be set in a child context.

In PHP 8.4, it is now possible.

On the other hand, initialisation in the global space is still forbidden.

PHP code

<?php

class x {
	protected readonly int $property;
}

class y extends x {
    function __construct() {
        $this->property = 5;
    }
}

$x = new y;
echo $x->property;

?>

Before

PHP Fatal error:  Uncaught Error: Cannot initialize readonly property x::$property from scope y

After

5

PHP version change

This behavior changed in 8.4.

Error Messages

Extension

© 2023-2026, Damien Seguy - Exakat