dpv21589 2014-05-14 16:53
浏览 30
已采纳

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

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.)

autoloader.php

<?php

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

spl_autoload_register("autoloadLib");

index.php

<?php

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

lib/wbp.Foo.php

<?php

namespace Foobar;

class Foo {
    public static function Bar(){
        return "foobar";
    }
}
  • 写回答

2条回答 默认 最新

  • doujia1871 2014-05-14 17:12
    关注

    In the autoload, the $className variable includes the namespace. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?