PHP回调函数和变量引用

时间:2016-05-03 18:10:26

标签: php scope reference

我正致力于解决"非常大的问题"在HackerRank上。目标是在不使用array_sum的情况下生成数组中所有元素的总和。为清楚起见,这里的示例代码与那里的代码略有不同。

这有效:

$arr = array( 
    1000000001,
    1000000002,
    1000000003,
    1000000004,
    1000000005
);

$total = 0;
array_walk($arr, 'totalize');
echo '*' . $total;

function totalize( $arr_item ) {
    global $total;
    $total += $arr_item;
}

我希望避免使用全局,以便将来使用回调函数时可以正常使用。但是,这不起作用。我将在代码后显示输出:

$arr = array( 
    1000000001,
    1000000002,
    1000000003,
    1000000004,
    1000000005
);

$total = 0;
array_walk($arr, 'totalize', $total);
echo '*' . $total;

function totalize( $arr_item, $key, &$total ) {
    $total += $arr_item;
    echo $arr_item . '.' . $key . '.' . $total . '<br />';
}

它将此作为输出:

1000000001.0.1000000001
1000000002.1.2000000003
1000000003.2.3000000006
1000000004.3.4000000010
1000000005.4.5000000015
*0

为什么$ total被正确加起来然后被放弃?

答案: 感谢@ miken32我发现这有效:

$arr = array( 
    1000000001,
    1000000002,
    1000000003,
    1000000004,
    1000000005
);

$total = 0;
array_walk($arr, function( $arr_item ) use ( &$total ) { totalize( $arr_item, $total ); } );
echo '*' . $total;

function totalize( $arr_item, &$total ) {
    $total += $arr_item;
    echo $arr_item . '.' . $total . '<br />';
}

它给出了这个输出:

1000000001.1000000001
1000000002.2000000003
1000000003.3000000006
1000000004.4000000010
1000000005.5000000015
*5000000015

2 个答案:

答案 0 :(得分:3)

对于这种特殊情况,您可以使用anonymous functionthe use keyword$total导入到该功能的范围内。

$arr = [
    1000000001,
    1000000002,
    1000000003,
    1000000004,
    1000000005
];

$total = 0;
array_walk($arr, function ($arr_item) use (&$total) {$total += $arr_item;});
echo '*' . $total;

答案 1 :(得分:2)

array_walk()的第三个参数不能作为参考传递。当您调用array_walk()时,它会使用您传递的值作为其第三个参数来初始化局部变量。然后它通过引用传递本地变量回调(因为这是你的回调定义的方式)。

但全局变量$total与传递给回调的变量($total的参数totalize())之间没有任何联系。如果您更改totalize()以显示全局变量$total的值,则可以自己查看。

实现目标的更合适方法是使用array_reduce()。文档中的第一个示例正是您问题的解决方案。