有没有办法从php闭包更新调用范围变量

时间:2015-05-24 08:20:42

标签: php php-5.6 php-closures

带有php闭包的

use关键字是一种非常明确的方法,可以将精心挑选的变量的范围扩展到闭包。

如果我们需要从闭包中更新调用函数范围中某个变量的值,有什么办法吗?

$total_strength = 0;
$all_cores->each(function($core) use ($total_strength) {
    $total_strength += $code->strength;
});

print('Cumulative cores' strength is: ' . $total_strength);

我总是得到0.如何解决?

1 个答案:

答案 0 :(得分:1)

你可以简单地传递参数by reference,像这样:

use (&$total_strength)
   //^ See here