首页 > 解决方案 > 未找到但使用命名空间定义的类

问题描述

我有一个DataBaseHelper在文件中定义的类DataBaseHelper.php

<?php

namespace Company\Project\System\DataBaseHelper;

use Company\Project\System\RepoLink;
use mysqli;
use mysqli_result;

class DataBaseHelper
{
    /* some cool stuff */
}

在一个名为helper.php(带有命名空间Company\Project\System;)的文件中,我使用以下 use 语句use Company\Project\System\DataBaseHelper\DataBaseHelper;::

 <?php

namespace Company\Project\System;

use Company\Project\DataBaseHelper\DataBaseHelper\DataBaseHelper;

class CustomHelper
{
    /* some cool stuff */

    public function getDownloadCount(): string
    {
        try {
            $query = "SELECT sum(count) c from downloads";

            // The next line is line 258
            $DBLink = new DataBaseHelper();

            $result = $DBLink->getAssocResult($DBLink->executeQuery($query));

            return $result["c"];
        } catch (\Exception $e) {
            // TODO: Errorhandling
            return "ERROR";
        }

    }

}

调用CustomHelper->getDownloadCount()会引发以下错误:

> [15-Sep-2019 07:48:09 Europe/Berlin] PHP Fatal error:  Uncaught Error: Class 'Company\Project\System\DataBaseHelper\DataBaseHelper'
> not found in
> /Applications/XAMPP/xamppfiles/htdocs/project/system/helper.php:258
> Stack trace:
>     #0 /Applications/XAMPP/xamppfiles/htdocs/project/manage/index.php(49):
> Company\Project\System\RepoHelper->getDownloadCount()
>     #1 {main}   thrown in /Applications/XAMPP/xamppfiles/htdocs/project/system/helper.php on
> line 258

命名空间是否缺少任何东西?里面的use Statementhelper.php是我的IDE(PHPStorm)自动生成的。

我不使用任何框架。

标签: php

解决方案


一个类对 PHP 文件不可用,除非该类是:

  1. 在该文件中声明;或者
  2. 在该文件直接或间接包含或需要的另一个 PHP 文件中声明

use语句仅将长命名空间类的别名声明为具有较短的本地名称。它不会自动包含任何文件。事实上,对于如何将命名空间类放在文件夹结构中,根本没有默认定义。

要在 上自动包含或要求类文件new,您需要使用spl_autoload_register实现注册自动加载器功能,或者让 composer 为您实现它。

您可以参考类似问题的答案以获取更多详细信息。

假设您以遵循PSR-4标准的方式使用 Composer,您的 PhpStorm 可能会建议命名空间。


推荐阅读