douzhan4522
2014-01-08 21:10
浏览 35
已采纳

spl_autoload_register尝试加载具有依赖项的类

How smart is spl_autoload_register? Does it know to "look ahead" for the class definition in other files before trying to include?

When I run my index.php page I'm seeing Fatal error: Class 'input\input' not found in /var/www/php/classes/input/date.php on line 4

index.php runs the following (after this block it creates an object from one of the classes, if I uncomment the one line everything works perfectly)

function my_autoloader() {
    //include_once "/var/www/php/classes/input/input.php"; //if this is uncommented, it fixes the problem, but I'm not sure why
    foreach (glob("/var/www/php/classes/*/*.php") as $filename)
    {
        require_once $filename;
    }
}
spl_autoload_register('my_autoloader');

is my syntax wrong? is spl_autoload_register supposed to function this way? many other files in these folders depend on eachother and the autoloader seems to "figure it out". I'm not sure why it is suddenly hung up on the "input" class in particular

图片转代码服务由CSDN问答提供 功能建议

spl_autoload_register有多聪明? 在尝试包含之前,是否知道其他文件中的类定义“向前看”?

当我运行我的index.php页面时,我看到 Fatal错误:Class'input 在第4行/var/www/php/classes/input/date.php中找不到\ input'

index.php运行以下命令(在此块之后它从一个块创建一个对象) 如果我取消注释一行,一切都能正常工作)

  function my_autoloader(){
 // include_once“/ var / www / php / classes / input /  input.php“;  //如果这是取消注释的,它解决了问题,但我不确定为什么
 foreach(glob(“/ var / www / php / classes / * / * .php”)为$ filename)
 {\  n require_once $ filename; 
} 
} 
spl_autoload_register('my_autoloader'); 
   
 
 

我的语法错了? spl_autoload_register应该以这种方式运行吗? 这些文件夹中的许多其他文件依赖于彼此,自动加载器似乎“弄明白”。 我不知道为什么它突然挂在“输入”类上,特别是

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duannei0044 2014-01-08 21:13
    已采纳

    You're using the autoloader in a wrong way. It is only supposed to load the classes you need for a specific request, not the whole folder.

    Read more about autoloading classes properly with some good examples: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanshan7261 2014-01-08 21:12

    You are using it wrongly.
    The autoload is used for autoloading only the given class name on the 1st argument of callback, not for loading all classes like you're doing.

    For example:

    spl_autoload_register(function ($class) {
     // ...
     $class = stream_resolve_include_path(sprintf("%s.php", $class));
     if ($class !== false) {
      require $class
     }
    });
    

    $class will contains the class to load it, so, you can use it to find the file containing this class at your filesystem.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题