【问题标题】:Uncaught Error: Class 'Document' not found未捕获的错误:找不到类“文档”
【发布时间】:2019-04-14 23:38:49
【问题描述】:

我想将我编写的代码分成更小的可管理文件。一个文件有超过 2500 行,我认为将它的一些代码放入单独的头文件中可能会更好。但是,只要我分离代码并运行它。我收到以下错误:

Uncaught Error: Class 'Document' not found

这是我large-file.php的代码:

<?php
require_once("common-head.php");

/* Some more code */
$document = new Document($document_html);

这是我common-head.php的代码:

<?php
/* Some code */
require_once('vendor/autoload.php');
use DiDom\Document;
/* Some more code */

这两个文件位于同一目录中,因此vendor/autoload.php 的路径不会改变。但是,如果代码像我上面显示的那样放在单独的文件中,我会收到错误:

Uncaught Error: Class 'Document' not found

如果我从common-head.php 中取出所有代码并将其放在我的large-file.php 中以代替require_once("common-head.php");。它可以正常工作,没有任何错误。我该如何解决这个问题?

【问题讨论】:

  • 您是否已将diDim\Document 添加到 psr 自动加载器?
  • Uncaught Error: Class 'Document' not found 该错误意味着 PHP 无法找到您在代码中使用的类名 'Document'。

标签: php class require


【解决方案1】:

只需在同一个文件中使用use

// large-file.php
use DiDom\Document;

require_once("common-head.php");

/* Some more code */
$document = new Document($document_html);

见 - PHP namespaces and "use"

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2020-11-10
    • 2021-12-03
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    相关资源
    最近更新 更多