PHP 使用命名空间自动加载不加载文件

PHP autoload with namespaces do not load file

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

<?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();
?>

class 人的文件保存在目录 root->include->Person 我在 class 文件中这样使用命名空间

<?php
namespace Person;

class Person{
    function __construct(){
        print 'autoload works';
    }
}
?>

如果我在浏览器中访问索引文件它returns 'Class file not found'。 我是否正确使用命名空间?

您尝试包括 包括/class.Person\Person.php

  1. 如果你的Os是linux,你一定知道/和\
  2. 是有区别的
  3. 文件夹名称中是否存在前缀 class?

稍微更改一下自动加载代码

<?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;
});
?>