duanen19871021
2016-12-07 03:57
浏览 90
已采纳

spl_autoload_register无法获得“使用”命名空间

#file1
spl_autoload_register(function($class){
    require_once "{$class}.php";
});

new classes\Foo();

#file2
namespace classes;
class Foo implements toolInterface {
    function __construct(){
        echo __CLASS__; 
    }

    public function tool(){

    }
}

I have a problem with spl_autoload_register, above example works fine, but when I try to use use classes it will have fatal error, anyone know how to solve this problem?

//fatal error
spl_autoload_register(function($class){
    require_once "{$class}.php";
});

use classes;
new Foo();

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

 #file1 
spl_autoload_register(function($ class){
 require_once“{$ class} .php  “; 
}); 
 
new classes \ Foo(); 
 
#file2 
namespace classes; 
class Foo实现toolInterface {
 function __construct(){
 echo __CLASS__;  
 
 
 
公共函数工具(){
 
} 
} 
   
 
 

我有一个spl_autoload_register问题,上面的示例工作正常, 但是当我尝试使用使用类时会出现致命错误,有人知道如何解决这个问题吗?

  //致命错误
spl_autoload_register(  function($ class){
 require_once“{$ class} .php”; 
}); 
 
use classes; 
new Foo(); 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douduan1953 2016-12-07 05:48
    已采纳

    The ability to refer to an external fully qualified name with an alias

    Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.

    PHP: Using namespaces: Aliasing/Importing

    So we need the fully qualified name

    use classes\Foo;
    new Foo();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douzhan1963 2016-12-07 04:08

    If you log the $class variable provided to the closure you have you'll note that the FQCN (Fully Qualified Class Name) is given. In your case:

    classes\Foo
    

    You will need to ensure the file path is correct for that.

    Or you could also use the de-facto standard - Composer - Don't mind the fact that the home page has a picture of a conductor.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题