lang/php/ VariableReferences


Consider the following example:

<?php
$a = array("a" => 42);
$b = $a;
$b["a"] = 43;
var_dump($a);
var_dump($b);
$c=&$a;
$c["a"]=44;
var_dump($a);
var_dump($b);
var_dump($c);

When we say $b=$a, PHP does copy-on-write so that when we say $b["a"]=43, PHP makes a copy of $a. If we don't want this to happen, we use & to make a reference. That is, with:

<?php
$a = array("a" => 42);
$b = $a;
$b["a"] = 43;
var_dump($a);
var_dump($b);
$c=&$a;
$c["a"]=44;
var_dump($a);
var_dump($b);
var_dump($c);

we will see that $c and $a really do point to the same object, whereas $b points to its own copy of $a.