使用命名空间时找不到PHP类

时间:2016-04-22 07:01:12

标签: php namespaces autoload spl-autoload-register

我是这个命名空间的新手。

我的基本目录中有2个类(单独的文件),比如说class1.php中的class2.phpsrc/

class1.php

namespace \src\utility\Timer;

class Timer{
    public static function somefunction(){

    }
}

class2.php

namespace \src\utility\Verification;
use Timer;

class Verification{
     Timer::somefunction();
}

当我执行class2.php时,我收到致命错误

  

PHP致命错误:路径/ to / class2.php中找不到类'Timer'   第***行

我在SO上的某处读过,我需要为此创建自动加载器。如果是这样,我该如何创建一个,如果没有,那么还有什么问题?

更新

我创建了一个自动加载器,它将require我的php脚本之上的所有必需文件。 所以,现在class2.php会像这样结束。

namespace \src\utility\Verification;
require '/path/to/class1.php'
use Timer;
//or use src\utility\Timer ... both doesn't work.

class Verification{
     Timer::somefunction();
}

这也不起作用,它表明找不到类。但是,如果我删除了所有namespacesuse。一切正常。

2 个答案:

答案 0 :(得分:11)

我们可以通过两种方式解决命名空间问题

1) We can just use namespace and require

2) We can use Composer and work with the autoloading!

第一种方式(命名空间和要求)方式

  

Class1.php(计时器类)

namespace Utility;

class Timer
   {
    public static function {}
   }
  

Class2.php(验证类)

namespace Utility;
require "Class1.php";

//Some interesting points to note down!
//We are not using the keyword "use" 
//We need to use the same namespace which is "Utility" 
//Therefore, both Class1.php and Class2.php has "namespace Utility"

//Require is usually the file path!
//We do not mention the class name in the require " ";
//What if the Class1.php file is in another folder?
//Ex:"src/utility/Stopwatch/Class1.php"  

//Then the require will be "Stopwatch/Class1.php"
//Your namespace would be still "namespace Utility;" for Class1.php

class Verification
   {
     Timer::somefunction();
   }

第二种方式(使用Composer和自动加载方式)

  

制作 composer.json 文件。根据你的例子" src / Utility"   我们需要在src文件夹之前创建一个composer.json文件。示例:在名为myApp的文件夹中,您将拥有composer.json文件和src文件夹。

   {
     "autoload": {
     "psr-4": {
        "Utility\\":"src/utility/"
        }
     }   
   }

现在转到该文件夹​​,在具有composer.json文件的文件夹位置打开终端。现在输入终端!

   composer dump-autoload

这将创建供应商文件夹。因此,如果您有一个名为" MyApp"的文件夹 你会看到vendor文件夹,src文件夹和composer.json文件

  

Timer.php(定时器类)

namespace Utility;

class Timer
     {
      public static function somefunction(){}
     }
  

Verification.php(验证类)

namespace Utility; 
require "../../vendor/autoload.php"; 
use Utility\Timer; 

class Verification
  {
     Timer::somefunction(); 
  }

当您拥有复杂的文件夹结构时,此方法更强大!!

答案 1 :(得分:1)

您将需要实现一个自动加载器,因为您已经在SO中阅读过它。

您可以在http://www.php-fig.org/psr/psr-4/查看自动加载标准PSR-4,您可以看到PSR-4自动加载的示例实现以及在此处处理多个名称空间的示例类实现https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md

相关问题