Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.
<?php
class Obj {
public $x;
}
function obj_inc_x($obj) {
$obj->x++;
return $obj;
}
$obj = new Obj();
$obj->x = 1;
$obj2 = obj_inc_x($obj);
obj_inc_x($obj2);
print $obj->x . ', ' . $obj2->x . "\n";
function scalar_inc_x($x) {
$x++;
return $x;
}
$x = 1;
$x2 = scalar_inc_x($x);
scalar_inc_x($x2);
print $x . ', ' . $x2 . "\n";
function &scalar_ref_inc_x(&$x) {
$x++;
return $x;
}
$x = 1;
$x2 =& scalar_ref_inc_x($x); scalar_ref_inc_x($x2);
print $x . ', ' . $x2 . "\n";
function array_inc_x($array) {
$array{'x'}++;
return $array;
}
$array = array();
$array['x'] = 1;
$array2 = array_inc_x($array);
array_inc_x($array2);
print $array['x'] . ', ' . $array2['x'] . "\n";
function &array_ref_inc_x(&$array) {
$array{'x'}++;
return $array;
}
$array = array();
$array['x'] = 1;
$array2 =& array_ref_inc_x($array); array_ref_inc_x($array2);
print $array['x'] . ', ' . $array2['x'] . "\n";