dongquexi1990
2016-02-19 14:49
浏览 61
已采纳

如何使用没有参数的spl_autoload_register?

I have a following directory structure in my project:

Test
--Cats
----Fatty.php // namespace: Test\Cats
--index.php

index.php:

spl_autoload_extensions(".php");
spl_autoload_register();

Test\Cats\Fatty::fattyMeow();

The error I'm getting:

Fatal error: Class 'Test\Cats\Fatty' not found in /var/www/public/Test/index.php on line 9

According to this comment at php.net, spl_autoload_register() should work just fine without any autoload function provided if namespaces match the directory structure of the project. So, Why the code above doesn't work? Or did I misunderstood something?

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

我的项目中有以下目录结构:

  测试
  -  Cats 
 ---- Fatty.php //名称空间:Test \ Cats 
  -  index.php 
   
 
 

index.php:

 <代码> spl_autoload_extensions( “PHP”); 
spl_autoload_register(); 
 \ NTEST \猫\脂肪:: fattyMeow(); 
   
 
 

我得到的错误:

致命错误:在 / var /中找不到类'Test \ Cats \ Fatty' www / public / Test / index.php第9行

根据这个评论在php.net, spl_autoload_register()应该可以正常工作,没有任何 autoload 如果名称空间与项目的目录结构匹配,则提供的功能。 那么,为什么上面的代码不起作用? 或者我误解了什么?

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

1条回答 默认 最新

  • dongyong8491 2016-02-19 15:16
    已采纳

    The reason why this is not working for you is because you are including the name of your main directory Test in your namespace. When you do this and you run spl_autoload it will think that directory exists as a sibling to index.php.

    To fix this adjust your namespaces and remove Test:

    in index.php:

    Cats\Fatty::fattyMeow();
    

    in Fatty.php:

    namespace Cats;
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题