【问题标题】:PHP autoload with namespaces do not load file带有命名空间的 PHP 自动加载不加载文件
【发布时间】: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


【解决方案1】:

稍微改变你的自动加载代码

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

【讨论】:

    【解决方案2】:

    您尝试包含 包含/.Person\Person.php

    1. 如果你的操作系统是linux,你必须知道/和\之间有区别
    2. 文件夹名称中是否存在前缀类?

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2014-04-13
      • 1970-01-01
      • 2011-08-06
      • 2015-07-15
      • 2012-05-21
      • 2011-04-08
      相关资源
      最近更新 更多