Dup Goto 📝

VariableReferences

PT2/aw/lang/php 07-31 13:46:41
To Pop
30 lines, 105 words, 651 chars Monday 2023-07-31 13:46:41

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.