我正在尝试获取Laravel中上传的Excel文件中的总页数。我上传的文件有3张。所以我希望得到$counter = 3
的输出。
代码:
$counter=0;
Excel::load($fileDetails['file_path'], function($sheet) use($counter) {
$sheet->each(function($sheet) use($counter) {
echo "It works</br>";
$counter++;
});
});
echo $counter; exit;
输出:
It works
It works
It works
0 //-- This is $counter, which is not get incremented. It has to be 3.
答案 0 :(得分:1)
use
就像传递参数一样。默认值是传递值,因此在函数内部进行的任何修改都不会反映在函数范围之外。
但是,如果您通过引用传递变量,则会反映更改。
将您的代码更新为:
$counter=0;
// add & to have var passed by reference
Excel::load($fileDetails['file_path'], function($sheet) use(&$counter) {
// add & to have var passed by reference
$sheet->each(function($sheet) use(&$counter) {
echo "It works</br>";
$counter++;
});
});
echo $counter;
exit;