您当前的位置:首页 > 网站建设笔记 >

discuz __autoload自动加载类文件的方法

0
<?php
if (function_exists("spl_autoload_register")) {
    spl_autoload_register(array("core", "autoload"));
}else{
    function __autoload($class) {
        return core::autoload($class);
    }
}

class core
{
    private static $_imports;

    public static function autoload($class) {
        $class = strtolower($class);
        if (strpos($class, "_") != false) {
            list($folder) = explode("_", $class);
            $file = "class/".$folder."/".substr($class, strlen($folder)+1);
        } else {
            $file = "class/".$class;
        }
        try {
            self::import($file);
            return true;
        } catch (Exception $exc) {
            $trace = $exc->getTrace();
            foreach ($trace as $log) {
                if (empty($log["class"]) && $log["function"] == "class_exists") {
                    return false;
                }
            }
            discuz_error::exception_error($exc);
        }
    }

    public static function import($name, $folder="", $force=true) {
        $key = $folder.$name;
        if (!isset(self::$_imports[$key])) {
            $path = DISCUZ_ROOT."/source/".$folder;
            if (strpos($name, "/") !== false) {
                $pre = basename(dirname($name));
                $filename = dirname($name)."/".$pre."_".basename($name).".php";
            } else {
                $filename = $name.".php";
            }
            if (is_file($path."/".$filename)) {
                include $path."/".$filename;
                self::$_imports[$key] = true;
                return true;
            } elseif (!$force) {
                return false;
            } else {
                throw new Exception("哎呀!系统文件丢失: ".$filename);
            }
        }
        return true;
    }
}

function libfile($libname, $folder="") {
	$libpath = "/source/".$folder;
	if (strstr($libname, "/")) {
		list($pre, $name) = explode("/", $libname);
		$path = "{$libpath}/{$pre}/{$pre}_{$name}";
	} else {
		$path = "{$libpath}/{$libname}";
	}
	//验证文件的合法路径
	//\w匹配字母或数字或下划线
	//\d匹配数字
	//\/匹配正斜框(/)
	//_匹配下划线
	//DISCUZ_ROOT常量等于D:\phpStudy\WWW\pcool\,在class_core.php文件中定义
	return preg_match('/^[\w\d\/_]+$/i', $path) ? realpath(DISCUZ_ROOT.$path.".php") : false;
}
?>

建站咨询

在线咨询真诚为您提供专业解答服务

咨询热线

137 1731 25507×24小时服务热线

微信交流

二维码终于等到你,还好我没放弃
返回顶部