PHP autoload classes from different directories

孤街浪徒 提交于 2019-12-13 09:45:56

问题


I have found this code that autoloads all classes within single directory, and it works pretty good. I would like to be able to extend it a bit to load classes from different paths (directories). Here is the code:

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

then in runt in my index.php file like :

Autoloader::init();

I'm using php 5.6


回答1:


You can add the other directories to the include path and if the class files have the same extension as your existing class files, your autoloader will find them

Before calling Autoloader:init(), do:

//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)


来源:https://stackoverflow.com/questions/38663356/php-autoload-classes-from-different-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!