【发布时间】:2018-05-01 04:30:29
【问题描述】:
嘿,我只是在学习命名空间和自动加载的工作原理。似乎无法让它工作可以使用一些帮助。我使用codeigniter,相关的目录结构是这样的:
root/
application/
classes/
testa/
TestClass.php
testb/
UserClass.php
html/
index.php
TestClass.php的内容是
namespace application\classes\testa;
class TestClass {
public $var = 'a default value';
public function displayVar() {
echo $this->var;
}
}
我尝试以这样的方式自动加载内容,它可以与 index.php 中的 classes 文件夹中的任何目录结构一起使用(我在网上找到了这段代码)
// autoload classes based on a 1:1 mapping from namespace to directory
// structure.
spl_autoload_register(function ($className) {
# Usually I would just concatenate directly to $file variable
# below
# this is just for easy viewing on Stack Overflow)
$ds = DIRECTORY_SEPARATOR;
$dir = __DIR__;
// replace namespace separator with directory separator (prolly
// not required)
$className = str_replace('\\', $ds, $className);
// get full name of file containing the required class
$file = "{$dir}{$ds}{$className}.php";
// get file if it is readable
if (is_readable($file)) require_once $file;
});
但是当我尝试在 codeigniter 视图中实例化一个类时
$obj = new application\classes\testa\TestClass();
我明白了
An uncaught Exception was encountered
Type: Error
Message: Class 'application\classes\testa\TestClass' not found
我做错了什么?我以前从未真正使用过命名空间或类,所以我有点迷路了。我认为自动加载器写错了(也许它是用于 Windows 机器的?)但我不确定。感谢您的帮助。
【问题讨论】:
-
这是您构建错误的路径。 index.php 中的
$dir = __DIR__;表示目录 html/ 。您无法在 html/ 下找到您的课程。尝试在屏幕上打印$file,看看您的文件路径是否正确。
标签: php class namespaces