【问题标题】:PHP Carry out variable out of closurePHP 执行变量出闭包
【发布时间】:2015-12-27 19:10:22
【问题描述】:

我正在使用 PHP 和 Laravel 构建一个应用程序。我从 maatwebsite 导入了 Excel 模块,以便轻松读取 Excel 文件中的内容。我正在使用下面的代码来读取 Excel。

Excel::load(Input::file('excel'), function ($reader) use ($request) {
   $sheets = $reader->get();
   foreach($sheets as $sheet) {
       //do logic
   }
}

现在我想知道是否可以从上面的函数中执行一个变量。我尝试了以下方法,但没有任何运气;

   $results = Excel::load(Input::file('excel'), function ($reader) use ($request) {
      $sheets = $reader->get();
      foreach($sheets as $sheet) {
          $error = 1
      }
      return $error;
   }

当我调试 $results 时,它包含来自 Excel maatwebsite 类的对象。有什么方法可以执行 $error 变量吗?

【问题讨论】:

  • 我不懂 Excel,但似乎您可以将结果添加到 $reader 对象,并从中读取,因为 load() 返回读取器对象。使用超出范围的范围变量通常不是一个好主意,即使这在 PHP 中也可以工作,因为它不是异步的(还不是?)。

标签: php function laravel


【解决方案1】:

为了回答我自己的问题,我修复了它:

$value = "";

Excel::load(Input::file('excel'), function ($reader) use ($request, &$value) {
   $sheets = $reader->get();
   foreach($sheets as $sheet) {
       $value = $error;
   }
}

echo $value;

【讨论】:

  • 另一种方法是在闭包内使用 global 关键字声明 $value ,如下所示:global $value
猜你喜欢
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2014-08-12
  • 2021-07-24
  • 2014-03-05
相关资源
最近更新 更多