自动加载namespace的方法(php)

namespace swoole;

class AutoLoad
{

    /**
     * Autoload root path.
     *
     * @var string
     */
    protected static $_autoload_root_path = '';

    /**
     * Set autoload root path.
     *
     * @param string $root_path
     * @return void
     */
    public static function set_root_path($root_path)
    {
        self::$_autoload_root_path = $root_path;
    }

    public static function requireClass($classname)
    {
      
        $class_path = str_replace('\\',DIRECTORY_SEPARATOR,$classname);
        if (strpos($classname, 'swoole\\') === 0)
        {
            $class_file = __DIR__ . substr($class_path, strlen('swoole')) . '.php';
        }else
        {
            if (self::$_autoload_root_path)
            {
                $class_file = self::$_autoload_root_path . DIRECTORY_SEPARATOR . $class_path . '.php';
            }
            if (empty($class_file) || !is_file($class_file))
            {
                $class_file = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . "$class_path.php";
            }
        }
        if (is_file($class_file))
        {
            require_once($class_file);
            if (class_exists($classname, false))
            {
                return true;
            }
        }
        return false;
        

    }
}
spl_autoload_register('swoole\AutoLoad::requireClass');

你可能感兴趣的:(自动加载namespace的方法(php))