0

我正在使用Laravel Excel项目将数据导出到 Excel 文件。我可以使用硬编码的月份和年份值生成具有正确数据的文件,就像这样

 public function month() {

    Excel::create('New file', function($excel) {
        $excel->sheet('New sheet', function($sheet) {
            $data = new ReportModel;
            $year = (int)2016;
            $month = (int)9;
            $donationData = $data->getDayData($month, $year);
            $sheet->loadView('exports.month', array('donationData' => $donationData));
        });
    })->download('xlsx');
}

但是,当我尝试制作月份和年份变量时,使用以下代码

 public function month($month, $year) {

    Excel::create('New file', function($excel) {
        $excel->sheet('New sheet', function($sheet) {
            $data = new ReportModel;
            $year = (int)$year;
            $month = (int)$month;
            $donationData = $data->getDayData($month, $year);
            $sheet->loadView('exports.month', array('donationData' => $donationData));
        });
    })->download('xlsx');
}

我收到以下错误

访问未声明的静态属性:App\Http\Controllers\ExportController::$year

我知道这取决于变量范围,但无法理解 PHP 文档。我努力了

$year = (int)self::$year;

但我得到了相同的结果。

4

2 回答 2

2

尝试在匿名函数范围内继承您需要访问的变量。

$example = function () use ($message) {
    var_dump($message);
};

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

就像是:

Excel::create('New file', function($excel) use ($year, $month) {
    $excel->sheet('New sheet', function($sheet) use ($year, $month) {
        $data = new ReportModel;
        $year = (int)$year;
        $month = (int)$month;
        $donationData = $data->getDayData($month, $year);
        $sheet->loadView('exports.month', array('donationData' => $donationData));
    });
})->download('xlsx');
于 2016-09-12T09:38:34.080 回答
1

你的假设是正确的,它是关于变量范围的,所以你需要在回调的范围内“导入”$year$month变量,像这样重构调用,它应该可以工作:

Excel::create('New file', function($excel) use ($year, $month) { ...
于 2016-09-12T09:39:16.340 回答