【发布时间】:2016-08-15 16:28:31
【问题描述】:
我是这个命名空间的新手。
我的基本目录中有 2 个类(单独的文件),例如 class1.php 和 class2.php 在目录 src/ 中。
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 致命错误:在 path/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();
}
这也不起作用,它显示未找到该类。但是,如果我删除所有namespaces 和use。一切正常。
【问题讨论】:
-
在您的 class2.php 中尝试使用 \src\Timer\Timer 作为计时器;
-
@ManinderpreetSingh 试过了。同样的问题。
-
我认为您应该查看Composer。命名空间只是类的唯一标识符。当一个类被实例化但它不存在但在预处理器抛出 T_FATAL 错误之前,PHP 的自动加载会被重载。通常的做法是然后将
\替换为/并从文件夹结构中加载它(为什么命名空间通常与目录结构匹配。 -
@ash 你能简单地告诉我 Composer 将如何帮助我的项目吗?我需要使用命名空间。我希望你已经阅读了我在问题中的更新。
-
它不会修复您的命名空间,它可以帮助您在代码中实例化类时加载类。结帐PHP The Right Way
标签: php namespaces autoload spl-autoload-register