When I execute the following code:
// autoload classes
spl_autoload_register(function($class) {
require_once("$class.php");
});
It works for all classes contained in the same directory as the script. However, any classes located in another directory will fail to load. The following solution works:
define('ABSOLUTE_PATH', "/var/www/application");
// autoload classes
spl_autoload_register(function($class) {
// class directories
$dir = array(ABSOLUTE_PATH,
ABSOLUTE_PATH . '/models');
foreach($dir as $path) {
$file = sprintf('%s/%s.php', $path, $class);
if(is_file($file)) {
require_once($file);
}
}
});
But this feels ugly. I’ve read that you can use namespaces but I can’t seem to get that or anything else to work. Can someone please show me a more elegant solution, if one exists, where I don’t have to hard-code the directory paths?
In order to autoload classes, you could use the PSR-0 standard at https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
The gist for SplClassLoader is located here https://gist.github.com/221634