是否有一种方法可以从php闭包中更新调用者作用域变量


php 5.6 - Is there a way to update caller scope variables from php closure

use关键字与php闭包是一个非常明确的方式来扩展范围的精挑精选变量闭包。

如果我们需要从闭包中更新调用函数范围内一些变量的值,是否有任何方法?

$total_strength = 0;
$all_cores->each(function($core) use ($total_strength) {
    $total_strength += $code->strength;
});
print('Cumulative cores' strength is: ' . $total_strength);

这里总是得到0。如何解决这个问题?

您可以简单地通过引用传递参数,像这样:

use (&$total_strength)
   //^ See here