首页 > 解决方案 > 类和扩展类中的 PHP 'USE' 运算符

问题描述

我试图了解如何USE在基类和扩展类中使用。我四处搜索,但我认为我没有正确的术语。

假设我的基类看起来像

namespace App\Classes;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Chart\Title;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;

class ExcelReport
{
    public $spreadsheet;

    public function __construct()
    {
        $this->spreadsheet = null;

    }
}

然后我扩展了那个课程

namespace App\Classes;


class MonthlyExcelReport extends ExcelReport
{
    public $id;

    public function __construct(int $id)
    {
        parent::__construct();
        $this->id = $id;

    }

    public function build()
    {
       $reader = IOFactory::createReader('Xlsx');
    }
}

我必须做什么才能IOFactory在扩展类中调用以识别use PhpOffice\PhpSpreadsheet\IOFactory;基类中存在的内容?

我目前收到此错误Class 'App\Classes\Gap\IOFactory' not found,我不想use在扩展类中重复所有这些语句。

标签: phpclass

解决方案


使用运算符用于“包含”一个类。如果您不使用“使用”运算符,则可以将其包含为“完整路径”。

在你的情况下:

$reader = IOFactory::createReader('Xlsx');

应该:

$reader = PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');

推荐阅读