Reputation: 2190
I try to pass a third parameter via reference to Phps array_walk_recursive
$field = 'foo';
array_walk_recursive($config, function($value, $key, &$field) {
$field = 'bar';
}, $field);
echo $field // 'foo'
Why is $field
still 'foo'
, though it has been passed to the function as reference?
Upvotes: 5
Views: 7020
Reputation: 2190
According to the php documentation of anonymous functions inherited variables of a closure have to be defined in the functions header with the keyword use
which leaves my example with:
function($value, $key) use (&$field) { ... }
Though the callback function inherits the parameters declared with use
from its parent which means from the scope/function it has been declared (not executed) in.
Upvotes: 13
Reputation: 4971
I had a similar problem, and I watched the changing of the values at the userdata parameter within the callback function. Here is what I discovered:
Assume this example-Code for testing:
$dataAr = array(
"key1" => "...",
"key2" => "...",
"sub" => array (
"skey1" => "...",
"skey2" => "...",
"skey3" => "..."
)
"key3" => "...",
"key4" => "...",
);
$returnData = array("call_path");
array_walk_recursive($dataAr, function ($value, $key, &$refField) {
echo "call: ".$key . ":".implode("-",$refField["call_path"])."\n";
$refField["call_path"][] = $key;
},
$returnData
);
echo "end :".implode("-",$returnData["call_path"])."\n";
Here are the results from my test:
call: key1 :.
call: key2 :.-key1
call: skey1:.-key1-key2
call: skey2:.-key1-key2-skey1
call: skey3:.-key1-key2-skey1-skey2
Until this point everything is like expected, but AFTER passing the sub-array:
call: key3:.-key1-key2
call: key4:.-key1-key2-key3
end : .
It seems to be, that the refference variable of the $userdata parameter in this function is always reseted to a previos value, when it comes from a sub array one level up.
So the refferece variable IF successfull change, but you cant see it after the function, because the starte value is restored in the last loop of each array.
I tested this in PHP 5.5.9
Upvotes: 0
Reputation: 55
<?php
$field = array('foo');
array_walk_recursive($field, function($value, $key) use(&$field) {
$field = 'bar';
});
print_r($field);
?>
Upvotes: 4