f.lorenzo
f.lorenzo

Reputation: 1226

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

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";
    }
}

Upvotes: 0

Views: 49

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

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.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

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.

PSR-4 is becoming a standard so the best way is to do this in that way

Upvotes: 1

Related Questions