【问题标题】:Passing variable by reference to an anonymous function not working通过引用匿名函数传递变量不起作用
【发布时间】:2018-06-20 15:17:07
【问题描述】:

我不知道为什么最后$count变量的值总是0,即使我通过引用传递变量并且代码进入循环并且变量增加了。

try {
        $count = 0;

        if ($request->hasFile('file')) {
            if ($request->file('file')->isValid()) {
                $file = $request->file('file');
                Excel::filter('chunk')->load($file->getRealPath())->chunk(100, function($results) use (&$count) {
                    foreach ($results as $row) {
                        $count++;
                    }
                });
            } else {
                throw new \Exception('File not valid');
            }
        }
        $request->session()->flash('alert-info', "{$count}");

    } catch (\Exception $e) { }

【问题讨论】:

  • 你尝试过简单的 var_dump-ing 吗?那里需要那些花括号吗?
  • var_dump($count) after $count++ 返回 1. 在匿名函数后为 0。
  • 这是一个对象吗?你可以使用属性而不是变量吗?即使您通过引用传递,变量范围可能仍然有效。使用会话变量?
  • 顺便说一句,您并没有通过引用“传递”任何东西;闭包通过引用“捕获”一个变量。
  • 如果Excel::filter('chunk')->load($file->getRealPath())->chunk(...)异步运行函数,那么在你稍后在这个函数中输出$count的值时闭包还没有运行(即你先输出$count,然后然后函数稍后运行,递增$count)。

标签: php laravel-5.2 closures anonymous-function


【解决方案1】:

这里有一些关于将变量传递给匿名函数的好例子:

http://php.net/manual/en/functions.anonymous.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多