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

标签 php php-5.6 php-closures

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

最佳答案

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

use (&$total_strength)
   //^ See here

关于php - 有没有办法从 php 闭包更新调用者范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421464/

相关文章:

php - 从 PHP 访问 MySQL 的访问被拒绝

xmlreader - PHP 中的错误? : XMLReader::readOuterXml 当输入为 UTF-8 时生成 "Input is not proper UTF-8"

php内置网络服务器缓存问题

php - PHP 5.3.2-1ubuntu4.2 不支持闭包

php - Silex 服务 - $app 参数或 "use ($app)"语句?

php - 在每个页面的页脚中使用 mysqli_close 有什么缺点吗?

php - file_get_contents ("php://input") 如果 POST 正文超过约 16 000 个字符,则为空

php - 从 Android 获取 PHP 中的 Post 数据