我的自动加载器和命名空间有问题。
自动加载器下方
<?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 的文件保存在目录 中。根->包含->人我在类文件中使用了这样的命名空间
<?php
namespace Person;
class Person{
function __construct(){
print 'autoload works';
}
}
?>
如果我在浏览器中访问索引文件,它会返回“找不到类文件”。我是否正确使用了命名空间?
最佳答案
稍微更改您的自动加载代码
<?php
spl_autoload_register( function( $class ) {
$folder = 'include/';
$prefix = '.class';
$ext = '.php';
//replace the backslash
$fullPath = $folder . str_replace( "\\", '/', $class ) . $prefix . $ext;
if( !file_exists( $fullPath ) ){
print 'Class file not found!';
return false;
}
require_once $fullPath;
});
?>
关于带有命名空间的 PHP 自动加载不加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65469107/