【问题标题】:How to call PHP property from string stored in a Variable如何从存储在变量中的字符串调用 PHP 属性
【发布时间】:2018-10-16 10:31:56
【问题描述】:

我正在使用 maatwebsite/excel 包,我想动态传递不同的文件类型作为第二个参数。
See function here

下面是变量:

$fileType = $request->input('fileType', 'xlsx');
$writerType = Excel::$fileType;

但我得到了错误:

访问未声明的静态属性:Maatwebsite\Excel\Excel::$fileType

我尝试使用大括号但不起作用:

Excel::${"fileType"};

如何传递变量?谢谢!

【问题讨论】:

  • 所以您希望 $fileType 的值是属性名称?喜欢Excel::xlsx$fileType 的值是多少?
  • 你的 Excel 的静态变量是如何声明的?
  • 为什么不使用变量$fileType 而不使用Excel::
  • @Jeff 是的,$fileType 将是 'xlsx' 或 'csv'。
  • @gogaz 这是 maatwebsite/excel 包。 laravel-excel.maatwebsite.nl/3.1/exports/export-formats.html

标签: php laravel maatwebsite-excel dynamic-variables laravel-excel


【解决方案1】:

您正确传递了变量。但是您的问题是 Maatwebsite\Excel\Excel 包含常量 XLSX 并且它不是属性。常量可以静态访问 Excel::XLSX 或使用constant 函数动态访问:

     $fileType = $request->input('fileType', 'xlsx');
     $writerType = constant('Excel::' . strtoupper($fileType));

【讨论】:

  • 它将得到Couldn't find constant Excel::XLSX。所以我使用完整的命名空间:$writerType = constant('\\Maatwebsite\\Excel\\Excel::' . strtoupper($fileType)); 它有效!谢谢。
【解决方案2】:
 return Excel::create('PatientList',function($excel) use ($variable){

            $excel->sheet('List',function($sheet) use ($variable){
                $sheet->fromArray($variable);
            });

        })->download($type);

当你下载file.pass $type时这样使用你的视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 2015-05-20
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多