简体   繁体   English

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

[英]spl_autoload_register couldn't get “use” namespace

#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? 我的spl_autoload_register有问题,上面的示例很好用,但是当我尝试使用use classes ,它将出现致命错误,有人知道如何解决此问题吗?

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

use classes;
new Foo();

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 . 请注意,对于命名空间名称(包含命名空间分隔符的完全限定的命名空间名称,例如Foo \\ Bar,而不是不包含全局名称的全局名称,例如FooBar),由于不需要使用反斜杠, 因为导入名称必须是完全限定的,并且不会相对于当前名称空间进行处理

PHP: Using namespaces: Aliasing/Importing PHP:使用名称空间:别名/导入

So we need the fully qualified name 所以我们需要完全限定的名称

use classes\Foo;
new Foo();

If you log the $class variable provided to the closure you have you'll note that the FQCN (Fully Qualified Class Name) is given. 如果您记录了提供给闭包的$class变量,则会注意到给出了FQCN(完全合格的类名)。 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. 或者,您也可以使用事实上的标准- 作曲家 -不要介意首页上有指挥家的图片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM