美文网首页
自动加载namespace的方法(php)

自动加载namespace的方法(php)

作者: 丶或情 | 来源:发表于2018-03-15 18:03 被阅读0次
    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)

          本文链接:https://www.haomeiwen.com/subject/ieohqftx.html