【发布时间】:2021-04-04 17:20:54
【问题描述】:
我的自动加载器和命名空间有问题。 在自动加载器下方
<?php
spl_autoload_register( function( $class ) {
$folder = 'include/';
$prefix = 'class.';
$ext = '.php';
$fullPath = $folder . $prefix . $class . $ext;
if( !file_exists( $fullPath ) ){
print 'Class file not found!';
return false;
}
require_once $fullPath;
});
?>
索引文件下方
<?php
require 'autoload.php';
//use backslash for namespace
$pers = new Person\Person();
?>
Person 类的文件保存在目录 root->include->Person 我像这样在类文件中使用了命名空间
<?php
namespace Person;
class Person{
function __construct(){
print 'autoload works';
}
}
?>
如果我在浏览器中访问索引文件,它会返回“找不到类文件”。 我是否正确使用了命名空间?
【问题讨论】:
-
echo $fullPath看看是否相关。 -
打印 $class 值时会发生什么?
-
我认为您的自动加载器没有考虑命名空间。您的结构需要类似于
include/class.Person\Person.php,这似乎不是您的意图。 -
如果我回显变量 $fullPath 输出是 include/class.Person\Person.php
-
现在,您知道问题所在了。包含/class.Person\Person.php 不存在。
标签: php class namespaces autoload