CKTIS / PHP
Memory, copies and references
Array assignment uses value semantics and can share storage until a write.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
$copy = $array; $alias =& $array;Array assignment uses value semantics and can share storage until a write. Changing an ordinary scalar slot in the copy leaves the original slot intact. A copied element containing an object still points to the same object. An explicitly referenced element can also remain shared across both arrays.
$n=2;$a=["plain"=>1,"obj"=>(object)["n"=>3],"ref"=>&$n];$b=$a;$b["plain"]=9;$b["obj"]->n=8;$b["ref"]=7;echo json_encode([$a["plain"],$a["obj"]->n,$a["ref"],$n]);
[1,8,7,7]
Examples
<?php
$n=2;$a=["plain"=>1,"obj"=>(object)["n"=>3],"ref"=>&$n];$b=$a;$b["plain"]=9;$b["obj"]->n=8;$b["ref"]=7;echo json_encode([$a["plain"],$a["obj"]->n,$a["ref"],$n]);
Result
[1,8,7,7]