[英]spl_autoload_register w/ multiple directories
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 为了自动加载类,您可以在以下网址使用PSR-0标准: 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 SplClassLoader的要点位于此处https://gist.github.com/221634
Yep. 是的 You can use spl_autoload_register to autoload classes from multiple directories.
您可以使用spl_autoload_register从多个目录自动加载类。 That includes classes with namespaces .
这包括带有名称空间的类。 :)
:)
6 lines of code, brackets included: 6行代码,包括方括号:
spl_autoload_register(function ($class) {
$file = str_replace('\\', '/', $class) . '.php';
if(file_exists($file)) {
require_once $file;
} // end if
});
Try it out and let me know if there's anything I can help with. 尝试一下,让我知道是否有什么我可以帮助的。
Cheers :) 干杯:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.