开发者

Question about a simple PHP Autoloader

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 $n开发者_Go百科ame . ".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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜