Reputation: 773
After looking through the web I have managed to build a working SPL_Autoload and use namespaces in it. It does work but it also looks a bit strange to me compared to all of the examples I was looking at and the documentation. Am I using everything and understanding it correctly?
$class looks up a class called subdir\timer and since it cannot find it goes to the SPL_autoload
$class = new subdir\timer;
The SPL_autoload is suppose to look for a file in the folder 'subdir' with a file 'timer' ending in either .php or .class.php (thanks to the SPL_extensions)
Now I am not really sure what is going on in register and SPL_autoload. When I tried register by itself it was not using the _extensions but when i added spl_autoload it worked fine. Only thing is I have never seen it setup like this in any examples so I really question this part
spl_autoload_extensions(".php,.class.php");
spl_autoload_register(function($class){
spl_autoload("$class");
});
What do you think, any things that cam be improved on or that I did wrong?
Upvotes: 3
Views: 4051
Reputation: 12655
I've tested it and it works for me:
set_include_path(__DIR__.'PATH_TO_LIB');
spl_autoload_extensions('.php,.class.php');
spl_autoload_register();
So you've set the correct include_path?
Further for namespaces and classnames there is a standard called PSR-0.
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
They also have a SplClassLoader which is a little bigger but also more flexible, although I wonder that you can only set one file extension. Well but search for PSR-0 autoloader
and you'll find more implementations. By the way there are also the standards PSR-1 and PSR-2 which are worth to know..
Upvotes: 3