【问题标题】:Is there a way to update caller scope variables from php closure有没有办法从 php 闭包更新调用者范围变量
【发布时间】:2015-08-05 22:31:14
【问题描述】:

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。如何解决这个问题?

【问题讨论】:

  • Pass it by reference -> use ( & $total_strength)
  • 太棒了!谢谢。请以正确的方式回复,我将标记为已接受。 :)

标签: php php-5.6 php-closures


【解决方案1】:

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

use (&$total_strength)
   //^ See here

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 2018-03-13
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多