【问题标题】:Cannot load class with require_once when using namespace使用命名空间时无法使用 require_once 加载类
【发布时间】:2023-04-10 01:32:02
【问题描述】:

我正在使用Slim 开发一个简单的REST API,但我遇到了一个奇怪的问题。基本上我配置了API 以通过composer使用自动加载器加载所有类:

"autoload": {
    "psr-4": {
        "App\\Controllers\\": "app/controllers",
        "App\\Helpers\\": "app/helpers",
        "App\\Models\\": "app/models",
        "App\\Services\\": "app/services",
        "Core\\": "src/core",
        "Core\\Helpers\\": "src/helpers",
        "Core\\Libraries\\": "src/libraries"
    }
}

我创建了一个名为GoogleSync 的类,它必须包含Google API php library,所以我通过以下方式包含:

<?php namespace Core\Libraries;

defined('BASEPATH') or exit('No direct script access allowed');

require_once __DIR__ . '/external/google-api-php-client/Google_Client.php';
require_once __DIR__ . '/external/google-api-php-client/contrib/Google_CalendarService.php';


class GoogleSync
{
    /**
     * Google API Client
     *
     * @var Google_Client
     */
    protected $client;

    public function __construct($api_settings)
    {
        var_dump(file_exists(__DIR__ . "/external/google-api-php-client/Google_Client.php"));
        $this->client = new Google_Client();
    }
}

我收到以下错误:

致命错误:未捕获的错误:找不到类“Core\Libraries\Google_Client” A:\Programmi\MAMP\htdocs\ci3-api\src\libraries\GoogleSync.php:44

如果我在 Google_Client 类中包含以下命名空间,原因很奇怪:

Core\Libraries

代码能够加载类。所以我怀疑require_once 无法注入类,因为有一个自动加载器逻辑,但我可能是错的。

另外,构造函数中的方法file_exist返回true

发生了什么事?

【问题讨论】:

  • 您在命名空间中调用它,因此它会尝试使用该命名空间,也许可以尝试像这样实例化它: $this->client = new \Google_Client();忽略命名空间。
  • 谢谢这个问题真的很容易解决,如果你回答我会接受的问题,祝你有美好的一天

标签: php namespaces slim-3


【解决方案1】:

您在命名空间中调用它,因此它会尝试使用该命名空间,也许可以尝试像这样实例化它:$this-&gt;client = new \Google_Client(); 以忽略命名空间。

Possible duplicate of this question.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2013-03-12
    • 2011-06-22
    • 2013-04-03
    • 2013-11-07
    • 2014-09-03
    • 2017-11-03
    相关资源
    最近更新 更多