无法访问 Laravel 控制器函数中的变量数据

Unable to access variable data in Laravel controller function

我正在使用 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');
}

我收到以下错误

Access to undeclared static property: App\Http\Controllers\ExportController::$year

我知道这取决于可变范围,但无法理解 PHP 文档。我试过了

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

但我得到了相同的结果。

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

$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');

你认为它是关于变量范围的假设是正确的,所以你需要 "import" 回调范围中的 $year$month 变量,像这样重构调用它应该有效:

Excel::create('New file', function($excel) use ($year, $month) { ...