Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing user data as reference to array_walk_recursive in Php

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?

like image 299
magic_al Avatar asked Jul 15 '14 06:07

magic_al


2 Answers

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.

like image 56
magic_al Avatar answered Nov 15 '22 00:11

magic_al


 <?php
        $field = array('foo');
        array_walk_recursive($field, function($value, $key) use(&$field) {
            $field = 'bar';
        });
        print_r($field);
        ?>
like image 21
jeddey Avatar answered Nov 15 '22 01:11

jeddey