如何解决代码点火器中缺少的类函数



我的控制器中有这个:

if (!defined('BASEPATH'))
exit('No direct script access allowed');
use xampphtdocsclientvendorphpofficephpspreadsheetsrcPhpSpreadsheetSpreadsheet;
use xampphtdocsclientvendorphpofficephpspreadsheetsrcPhpSpreadsheetWriterXlsx;

但这是我在运行代码后看到的错误

Message: Class 'xampphtdocsclientvendorphpofficephpspreadsheetsrcPhpSpreadsheetSpreadsheet' not found

Filename: C:xampphtdocsclientapplicationcontrollersadminHome.php

您似乎混淆了useinclude/require

use语句用于命名空间导入和别名。上面写着";当我使用类名Foo时,我的实际意思是SomethingSomethingFoo。这个全名可能看起来像Windows文件路径,但这里的实际上是PHP的命名空间分隔符,与磁盘上的位置没有直接关系。

在这种情况下,你会写:

// Alias these class name so I don't have to write them in full in this file
use PhpSpreadsheetSpreadsheet;
use PhpSpreadsheetWriterXlsx;

如果要引用特定文件中的代码,则需要include和require关键字族。他们说";加载这个PHP文件,并执行其中的代码,包括类和函数定义。

因此,以下内容是有意义的:

// Load the file
require_once 'xampphtdocsclientvendorphpofficephpspreadsheetsrcPhpSpreadsheetSpreadsheet.php';
require_once 'xampphtdocsclientvendorphpofficephpspreadsheetsrcPhpSpreadsheetWriterXlsx.php';

但是,大多数PHP库都是自动加载的,所以不必手动命名每个文件。通常,您甚至不需要配置自动加载本身,而是使用Composer来安装它们,它会为您设置自动加载程序。

然后,您将在代码的主要入口点中写道:

require_once 'vendor/autoload.php';

这些类在被引用时会自动加载。请注意,您可能仍然想要use行,而那些确实必须在每个文件中(因为每个文件可以使用相同的别名来引用不同的类(。

最新更新