PHP从不同目录自动加载类

PHP从不同目录自动加载类,php,autoload,Php,Autoload,我发现这段代码可以在一个目录中自动加载所有类,而且效果非常好。我希望能够对它进行一些扩展,以便从不同的路径(目录)加载类。代码如下: define('PATH', realpath(dirname(__file__)) . '/classes') . '/'; define('DS', DIRECTORY_SEPARATOR); class Autoloader { private static $__loader; private function

我发现这段代码可以在一个目录中自动加载所有类,而且效果非常好。我希望能够对它进行一些扩展,以便从不同的路径(目录)加载类。代码如下:

  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();

我使用的是PHP5.6

您可以将其他目录添加到include路径,如果类文件具有与现有类文件相同的扩展名,您的自动加载程序将找到它们

在调用自动加载程序: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)

你有问题吗?这个网站是用来提问的,不是用来转储你的待办事项列表并期望其他人为你做工作的地方。@Marc B,是的,我的问题是如何扩展这个类来扫描多个目录。我不指望有人做我的工作。我已经提供了一段代码,我需要帮助。如果你不想帮忙,那么就不要浪费这个空间,让别人说些聪明的话。我们修复代码,我们不会为你写代码,也不会帮助你设计系统。那是你的工作。你试着做点什么,我们(也许)试着帮你解决。