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
# (1) Objects are always passed by reference and returned by reference
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";
# (2) Scalars are not passed by reference or returned as such
function scalar_inc_x($x) {
$x++;
return $x;
}
$x = 1;
$x2 = scalar_inc_x($x);
scalar_inc_x($x2);
print $x . ', ' . $x2 . "\n";
# (3) You have to force pass by reference and return by reference on scalars
function &scalar_ref_inc_x(&$x) {
$x++;
return $x;
}
$x = 1;
$x2 =& scalar_ref_inc_x($x); # Need reference here as well as the function sig
scalar_ref_inc_x($x2);
print $x . ', ' . $x2 . "\n";
# (4) Arrays use pass by value sematics just like scalars
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";
# (5) You have to force pass by reference and return by reference on arrays
function &array_ref_inc_x(&$array) {
$array{'x'}++;
return $array;
}
$array = array();
$array['x'] = 1;
$array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig
array_ref_inc_x($array2);
print $array['x'] . ', ' . $array2['x'] . "\n";