当我执行以下代码时:
// autoload classes
spl_autoload_register(function($class) {
require_once("$class.php");
});
它适用于与脚本位于同一目录中的所有类。但是,位于另一个目录中的任何类都将无法加载。以下解决方案有效:
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);
}
}
});
但这感觉很难看。我已经阅读了you can use namespaces,但我似乎无法使用其他任何东西。有人可以告诉我一个更优雅的解决方案,如果存在,我不需要对目录路径进行硬编码吗?
答案 0 :(得分:1)
为了自动加载课程,您可以在https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md使用PSR-0标准
SplClassLoader的要点位于https://gist.github.com/221634
答案 1 :(得分:0)
是的。您可以使用spl_autoload_register从多个目录自动加载类。这包括具有命名空间的类。 :)
6行代码,包括括号:
spl_autoload_register(function ($class) {
$file = str_replace('\\', '/', $class) . '.php';
if(file_exists($file)) {
require_once $file;
} // end if
});
尝试一下,让我知道是否有任何我可以提供的帮助。
干杯:)