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

Cannot acquire reference to readonly property %s::$%s

Description

It is not possible to create a reference to a readonly property. The property is readonly and cannot be changed. On the other hand, references are never readonly, and provide read and write access to the data. PHP has no way to check that the reference is readonly. Hence, references on readonly properties are not allowed.

Example

<?php

class Test {
    public readonly int $property;

    public function init() {
        $this->property = 1;
    }
}

$test = new Test;
$test->init();

try {
    foreach ($test as &$property) {}
} catch (Error $e) {
    echo $e->getMessage(), \n;
}

?>

Literal Examples

  • Cannot acquire reference to readonly property Test::$property

Alternatives

  • Remove the readonly option on the property.
  • Remove the reference to the property.