PHP 回调函数和变量引用

标签 php scope

我正致力于解决 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 加起来正确但后来被放弃了?

最佳答案

array_walk() 传递给回调的第三个参数不是通过引用传递的,无论您在回调的签名中放入什么。对于这种特殊情况,您可以使用 anonymous functionthe use keyword通过引用将 $total 导入函数的作用域。

$arr = [
    1000000001, 1000000002, 1000000003, 1000000004, 1000000005
];
$total = 0;
array_walk($arr, function ($arr_item) use (&$total) {
    echo ($total += $arr_item) . "\n";
});
echo '*' . $total;

关于PHP 回调函数和变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011395/

相关文章:

javascript - 在不同的 HTML 页面之间传递数据

ruby-on-rails - 如何在 Rails 中编写作用域?

r - 应用系列功能的范围如何?

javascript - 如何在回调函数中访问全局范围变量? [JS]

python - Python timeit 设置中的局部变量

php - 从一个表(mysql)中获取每个标题并从另一个表中获取url并使用title提取每个url上的数据

php - fatal error : Uncaught Error: Call to undefined function ereg_replace() PHP 7

php - YII 服务器迁移。内部服务器错误。 CDb异常

php - 有效且非冗余的 PHP 代码

javascript - 从回调中访问 `this`