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

Sho*_*waz 1 php php-closures php-5.6

use 带有 php 闭包的关键字是将精选变量的范围扩展到闭包的一种非常清晰的方法。

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

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

print('Cumulative cores' strength is: ' . $total_strength);
Run Code Online (Sandbox Code Playgroud)

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

Riz*_*123 5

您可以简单地通过引用传递参数,如下所示:

use (&$total_strength)
   //^ See here
Run Code Online (Sandbox Code Playgroud)