-3
我发现这个代码可以自动加载单个目录中的所有类,并且它工作得很好。我希望能够扩展它来加载不同路径(目录)的类。下面是代码:来自不同目录的PHP自动加载类
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文件:
Autoloader::init();
我使用PHP 5.6
你有问题吗?这个网站是问题,而不是一个地方转储你的待办事项列表,并期望别人为你做你的工作。 –
@Marc B,是的我的问题是如何扩展类来扫描多个目录。我不指望任何人做我的工作。我提供了一段代码,我需要帮助。如果你不想帮忙,那么不要浪费这个空间,让其他人说一些聪明的东西。 – Alko
我们修复代码,我们不会为您编写代码,或帮助您设计系统。这是你的工作。你试着做一些事情,我们(也许)试着帮助解决它。 –