PHP - most lightweight psr-0 compliant autoloader

后端 未结 7 854
猫巷女王i
猫巷女王i 2020-12-01 09:55

I have a tiny application that i need an autoloader for. I could easily use the symfony2 class loader but it seems like overkill.

Is there a stable extremely lightw

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 10:04

    An exact equivalent of the answer @hakre provided, just shorter:

    function autoload($class) {
      $path = null;
    
      if (($namespace = strrpos($class = ltrim($class, '\\'), '\\')) !== false) {
        $path .= strtr(substr($class, 0, ++$namespace), '\\', '/');
      }
    
      require($path . strtr(substr($class, $namespace), '_', '/') . '.php');
    }
    

    You can also set the base directory by changing $path = null; to another value, or just do like this:

    $paths = array
    (
        __DIR__ . '/vendor/',
        __DIR__ . '/vendor/phunction/phunction.php',
    );
    
    foreach ($paths as $path)
    {
        if (is_dir($path) === true)
        {
            spl_autoload_register(function ($class) use ($path)
            {
                if (($namespace = strrpos($class = ltrim($class, '\\'), '\\')) !== false)
                {
                    $path .= strtr(substr($class, 0, ++$namespace), '\\', '/');
                }
    
                require($path . strtr(substr($class, $namespace), '_', '/') . '.php');
            });
        }
    
        else if (is_file($path) === true)
        {
            require($path);
        }
    }
    

提交回复
热议问题