Question about simple PHP autoloader

I just learned about PHP namespaces and started creating a simple startup function. What was it:

function __autoload($name) { echo $name . "<br />"; require_once $name . ".php"; } 

So this works if I do not use any aliases or importers, for example. use MainNamespace\Subnamespace , because if I did this, 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(); 

works because $name at startup will become GreatApp\Models\User , so GreatApp\Models\User.php will be found. But when I do this:

 use GreatApp\Models; new User(); 

it fails because now $name just User and User.php will not be found. How to configure autoload?

+4
source share
1 answer

The full namespace path is always passed to the autoloader, regardless of how you import the namespace and reference the class. It should work.

Only the __autoload function itself must belong to the main (root) namespace

+1
source

Source: https://habr.com/ru/post/1316662/


All Articles