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?
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.
<?php
$field = array('foo');
array_walk_recursive($field, function($value, $key) use(&$field) {
$field = 'bar';
});
print_r($field);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With