我发现这段代码可以自动加载单个目录中的所有类,而且效果非常好。我希望能够扩展它以从不同的路径(目录)加载类。这是代码:
define('PATH', realpath(dirname(__file__)) . '/classes') . '/';
define('DS', DIRECTORY_SEPARATOR);
class Autoloader
{
private static $__loader;
private function __construct()
{
spl_autoload_register(array($this, 'autoLoad'));
}
public static function init()
{
if (self::$__loader == null) {
self::$__loader = new self();
}
return self::$__loader;
}
public function autoLoad($class)
{
$exts = array('.class.php');
spl_autoload_extensions("'" . implode(',', $exts) . "'");
set_include_path(get_include_path() . PATH_SEPARATOR . PATH);
foreach ($exts as $ext) {
if (is_readable($path = BASE . strtolower($class . $ext))) {
require_once $path;
return true;
}
}
self::recursiveAutoLoad($class, PATH);
}
private static function recursiveAutoLoad($class, $path)
{
if (is_dir($path)) {
if (($handle = opendir($path)) !== false) {
while (($resource = readdir($handle)) !== false) {
if (($resource == '..') or ($resource == '.')) {
continue;
}
if (is_dir($dir = $path . DS . $resource)) {
continue;
} else
if (is_readable($file = $path . DS . $resource)) {
require_once $file;
}
}
closedir($handle);
}
}
}
}
然后在我的index.php文件的runt中,如:
Autoloader::init();
我使用的是php 5.6
答案 0 :(得分:0)
您可以将其他目录添加到包含路径,如果类文件与现有类文件具有相同的扩展名,则自动加载器会找到它们
在调用Autoloader:init()
之前,请执行:
//directories you want the autoloader to search through
$newDirectories = ['/path/to/a', '/path/to/b'];
$path = get_include_path().PATH_SEPARATOR;
$path .= implode(PATH_SEPARATOR, $newDirectories);
set_include_path($path)