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

Indirect Modification In Clone

__clone is used to apply modifications during the cloning operation. It could also be used to change the original object.

PHP code

<?php

class X {
    readonly public int $p;
    
    function foo() {
        $this->p = 2;
    }
    
    function __clone() {
        $ref = &$this->p;
    }
}

$x = new x;
clone $x;

?>

Before

PHP Parse error:  syntax error, unexpected identifier "readonly", expecting "function" or "const" 

Parse error: syntax error, unexpected identifier "readonly", expecting "function" or "const" 

After

PHP Fatal error:  Uncaught Error: Cannot indirectly modify readonly property X::$p

Fatal error: Uncaught Error: Cannot indirectly modify readonly property X::$p

PHP version change

This behavior changed in 8.1.

Error Messages

Extension

© 2023-2026, Damien Seguy - Exakat