1]; // Unused reference $array2 = $array1; // reference now also applies to $array2 ! $array2[1]=22; // (changing [0] will not affect $array1) print_r($array1); ?> Produces:
Array
(
[0] => 1
[1] => 22 // var_dump() will show the & here
)
I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function: <?php
$array1 = array(1,2); $x = &$array1[1]; $array2 = $array1;
unset($x); // Array copy is now unaffected by above reference $array2[1]=22; print_r($array1); ?> Produces:
Array
(
[0] => 1
[1] => 2
)
Radek at cz (26-Apr-2008 02:35)
It took me a long while until I fully understood the sentence mentioned above:
"They (references) are not like C pointers; instead, they are symbol table aliases."
Here is a little example to that.
<?php class AnyClass {
public $member;
public function __construct($val) { $this->member = $val;
}
}
$manyObjects = array(); $obj = null;
for($i = 0; $i < 5;$i++) { $obj = new AnyClass($i); // create new instance $manyObjects[] = &$obj;