Php 在Linux上使用名称空间和目录自动加载类
嘿,我只是在学习名称空间和自动加载是如何工作的。似乎无法使其工作,可能需要一些帮助。我使用codeigniter,相关目录结构如下:Php 在Linux上使用名称空间和目录自动加载类,php,class,namespaces,Php,Class,Namespaces,嘿,我只是在学习名称空间和自动加载是如何工作的。似乎无法使其工作,可能需要一些帮助。我使用codeigniter,相关目录结构如下: root/ application/ classes/ testa/ TestClass.php testb/ UserClass.php html/ index.php TestClass.php的内容
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;
}
}
我尝试以这样一种方式自动加载内容,它将与classes文件夹中的任何目录结构一起工作,如index.php(我在网上找到了这段代码)
但是当我试图在codeigniter视图中用
$obj = new application\classes\testa\TestClass();
我明白了
An uncaught Exception was encountered
Type: Error
Message: Class 'application\classes\testa\TestClass' not found
我做错了什么?我以前从未真正使用过名称空间或类,所以我有点迷路了。我认为自动加载器写错了(可能是针对Windows机器?),但我不确定。谢谢您的帮助。因为您是在windows计算机上运行的,所以我假设root位于C: 在index.php中,
$file=“{$dir}{$ds}{$className}.php”代码>将被删除
C:\root\html\application\classes\testa\TestClass.php
在那里找不到TestClass.php
正确的文件路径应该是
$file = "{$dir}{$ds}..{$ds}{$className}.php";
哪一个是
C:\root\html\..\application\classes\testa\TestClass.php
。\
表示父目录。感谢您的帮助。我设法弄明白了。我为autoloader使用了这个选项,它为类dir提供了正确的路径
spl_autoload_register(function ($className) {
// $ds = '/';
$ds = DIRECTORY_SEPARATOR;
// $dir = the path to this file (index.php), it always gives
// path to the current file
$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 = '../' . $className . ".php";
// get file if it is readable
if (is_readable($file)) require_once $file;
});
顺便说一句,我使用的是Linux,而不是windows这是您构建错误的路径<代码>$dir=\uuuu dir\uuuuu表示目录html/。在html/下找不到您的类。尝试在屏幕上打印$file
,以查看文件路径是否正确。
spl_autoload_register(function ($className) {
// $ds = '/';
$ds = DIRECTORY_SEPARATOR;
// $dir = the path to this file (index.php), it always gives
// path to the current file
$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 = '../' . $className . ".php";
// get file if it is readable
if (is_readable($file)) require_once $file;
});