简体   繁体   English

使用具有自动加载功能的名称空间

[英]Using namespaces with autoloading

So i have got this small piece of code that auto loads the classes. 所以我有一小段代码可以自动加载类。 Everything is going allright until i add namespaces. 在我添加名称空间之前,一切都很顺利。 I get the error that it can't find the Class. 我得到错误,它无法找到类。 But when i remove the namespace it works again. 但是,当我删除命名空间时,它再次起作用。 (It also works when i include the wbp.Foo.php directly.) (当我直接包含wbp.Foo.php时它也有效。)

autoloader.php autoloader.php

<?php

function autoloadLib($className){
    $filename = "lib/wbp." . $className . ".php";
    if(is_readable($filename)){
        require $filename;
    }
}

spl_autoload_register("autoloadLib");

index.php 的index.php

<?php

include "autoloader.php";
use Foobar\Foo;
echo Foo::Bar();

lib/wbp.Foo.php LIB / wbp.Foo.php

<?php

namespace Foobar;

class Foo {
    public static function Bar(){
        return "foobar";
    }
}

If you start with namespaces, you should simple read PSR-4 documentation at http://www.php-fig.org/psr/psr-4/ - there is also example of autoloader. 如果从名称空间开始,您应该在http://www.php-fig.org/psr/psr-4/上阅读PSR-4文档 - 还有自动加载器的示例。

PSR-4 is becoming a standard so the best way is to do this in that way PSR-4正在成为一种标准,所以最好的方法是以这种方式做到这一点

In the autoload, the $className variable includes the namespace. 在自动加载中, $className变量包含命名空间。 You need to either move the class into a file/folder structure that includes the namespace or remove the namespace from the classname and just load based on the class. 您需要将类移动到包含命名空间的文件/文件夹结构中,或者从类名中删除命名空间,然后根据类加载。 I suggest the former simply because the whole point of namespaces is to allow two different class definitions with the same name. 我建议前者只是因为命名空间的整个要点是允许两个不同的类定义具有相同的名称。 You can't really have two files in the same space on disk with the same name. 在磁盘上具有相同名称的同一空间中,您实际上不能有两个文件。 Renaming the $className could be as simple as str_replace('\\\\', '.', $className) and renaming your class to wbp.NameSpace.ClassName.php . 重命名$className可以像str_replace('\\\\', '.', $className)一样简单,并将您的类重命名为wbp.NameSpace.ClassName.php

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

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