【问题标题】:How the Class file is including in another file php using the namesapce and Use?类文件如何使用命名空间和使用包含在另一个文件 php 中?
【发布时间】:2014-04-08 19:59:18
【问题描述】:

我在 Errors.php 中有一个名为 Errors 的类

namespace MyClass;
    class Errors
    {
        private $_CODES = array(
            301 => array(
                "code"=> 301,
                "message"=> "User With ID Not Found",
                "type"=> "Error"
            )
        );


        public static function getError($code)
        {
            return $this->_CODES[$code];
        }

在 Myclass.php 我有

namespace MyClass;

use MyClass\Errors;

require'vendor/autoload.php'; 

在 Myclass 里面我有一个函数,我正在检查错误

echo Errors::getError(301);

显示类 Myclass not found 错误

Fatal error: Class 'Myclass\Errors' not found in /var/www/Myclass/Myclass.php

我在这里错过了什么?

【问题讨论】:

  • 您将Errors.php 存储在哪里?
  • 显示autoload.php中的代码
  • require_once DIR 。 '/作曲家' 。 '/autoload_real.php';返回 ComposerAutoloaderInitddb04cf330f79dfb9cb9654960258d63::getLoader();

标签: php class namespaces composer-php


【解决方案1】:

你必须包括你的Errors.php

【讨论】:

  • 他使用作曲家的自动加载器
  • 自动加载是为了摆脱对类加载的显式使用 includerequire
  • 毫无疑问。仍然,Errors.php 必须包含在内,但目前似乎没有。
【解决方案2】:

composer 自动加载器与PSR4 标准兼容。在您当前的解决方案中,文件Errors.php 必须放在名为MyClass 的子文件夹中。 Read more

【讨论】:

    【解决方案3】:

    您似乎正在使用 Composer 的自动加载器。 您是否修改了“composer.json”以使其为您加载?

    可能是这样的:

    "autoload": { "classmap": ["path/to/your/source/directory"] }

    PSR-4 style which is described in official documentation

    【讨论】:

      【解决方案4】:

      此问题已解决。 Errors.php 如下所示。

      class Errors{
          private static $_CODES = array(
              301 => array(
                "code"=> 301, 
                "message"=> "User With ID Not Found", 
                "type"=> "Error"
              )
          ); 
      
          public static function getError($code) { 
              return self::$_CODES[$code]['message'];
          }
      }
      

      我添加了 require_once "Errors.php";在 MyClass.php 文件中,现在我可以调用函数echo Errors::getError(301)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 2014-05-02
        • 2011-07-24
        • 2019-08-24
        • 1970-01-01
        相关资源
        最近更新 更多