Reputation: 88189
I was just learning aboutt PHP namespaces and starting to create a simple autoload function. What O did was:
function __autoload($name) {
echo $name . "<br />";
require_once $name . ".php";
}
So, this works if I do not use any aliasing or importing statements eg. use MainNamespace\Subnamespace
because if I did that, assuming i have:
\GreatApp\Models\User.php
\GreatApp\Models\Project.php
\GreatApp\Util\Util.php
\GreatApp\Util\Test\Test.php
if I try to do:
new GreatApp\Models\User();
it works because $name
in autoload will become GreatApp\Models\User
so GreatApp\Models\User.php
is found. But when I do:
use GreatApp\Models;
new User();
it fails because now $name
is just User
and User.php
will not be found. How should I setup autoloading then?
Upvotes: 4
Views: 1662
Reputation: 29965
Full namespace path is always passed to the autoloader no matter how you import namespace and reference a class. It should work.
Just the __autoload function itself should belong to main (root) namespace
Upvotes: 1