1.2.1013. Readonly Property Changed By Cloning

Readonly properties may be changed when cloning. This may happen in the __clone magic method.

In that method, a new object is being created. It is acting like a constructor, and may tweak some of the values of the original object, before assigning them to the new object.

<?php

class x {
     public readonly int $p;

     function __construct($p) {
             $this->p = $p;
     }

     function __clone() {
             // This is possible in a clone, and only once
             $this->p = $this->p + 1;

             // This second call is not possible, as the property was set just above
             $this->p = $this->p + 2;
     }
}

$a = new x(1);
print_r(clone $a);

?>

1.2.1013.1. Specs

Short name

Php/ReadonlyPropertyChangedByCloning

Rulesets

All, CompatibilityPHP53, CompatibilityPHP54, CompatibilityPHP55, CompatibilityPHP56, CompatibilityPHP70, CompatibilityPHP71, CompatibilityPHP72, CompatibilityPHP73, CompatibilityPHP74, CompatibilityPHP80, CompatibilityPHP81, CompatibilityPHP82

Exakat since

2.5.3

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Available in

Entreprise Edition, Exakat Cloud