带有命名空间的 PHP 自动加载不加载文件

标签 php class namespaces autoload

我的自动加载器和命名空间有问题。
自动加载器下方

<?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/

相关文章:

php - 在 Yii 中更改错误 'cannot be blank'

php - Generator::send 是如何工作的?

使用 MySQL 显示表状态的 php 日期格式

python - 如何在 Python 中从继承的类中设置和获取父类属性?

excel - 用字符串变量替换字符串 - 错误 91

php - 在 Symfony 2 项目中安装 Doctrine 扩展会导致 fatal error

C#、Unity - 单个函数采用多个不同的对象

javascript - canvasJS 通过直接传递一个对象来插入新的数据点

python - 将属性分配给特定的函数实例

r - 从自身内部获取封装函数的属性