I’ve got three functions, foo, bar and baz, which, from my point of view, should produce identical results. However, I’m stuck with a problem that references are shared between recursive function calls.
$array = array(
'subs' => array(
'a' => 1,
'b' => 2,
),
);
function foo(&$array, $value, $callAgain = true) {
$subs =& $array['subs'];
foreach ($subs as &$sub)
$sub = $value;
if ($callAgain) {
$copy = $array;
foo($copy, $value + 1, false);
}
}
function bar(&$array, $value, $callAgain = true) {
foreach ($array['subs'] as &$sub)
$sub = $value;
if ($callAgain) {
$copy = $array;
bar($copy, $value + 1, false);
}
}
function baz(&$array, $value, $callAgain = true) {
foreach ($array['subs'] as $key => $sub)
$array['subs'][$key] = $value;
if ($callAgain) {
$copy = $array;
baz($copy, $value + 1, false);
}
}
foo($array, 3);
var_dump($array);
bar($array, 3);
var_dump($array);
baz($array, 3);
var_dump($array);
This code produces the following results:
array
'subs' =>
array
'a' => int 4
'b' => int 4
array
'subs' =>
array
'a' => int 3
'b' => int 4
array
'subs' =>
array
'a' => int 3
'b' => int 3
However, I expect all of them to return 3, 3, because copies of the array are passed to recursive calls.
How to fix the first two functions to make them return 3, 3? I’d prefer not to use syntax of the baz function, because it’s very verbose.
I think you have answered your own question–
bazIS the way to get the behavior you want. The other two functions are behaving as intended in PHP, at least according to the manual page on What References Do: