You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.9 KiB

<?php
namespace LaneWeChat;
/**
* 自动载入函数类
*
* 该类用于自动加载指定命名空间下的类文件,以便在需要时自动实例化类。
*
* Created by Lane.
* User: lane
* Date: 14-10-15
* Time: 下午6:13
* E-mail: lixuan868686@163.com
* WebSite: http://www.lanecn.com
*/
class Autoloader {
const NAMESPACE_PREFIX = 'LaneWeChat\\'; // 定义命名空间前缀,用于识别类名
/**
* 向PHP注册自动载入函数
*
* 通过此方法注册自动载入函数,当尝试实例化一个未定义的类时,将自动调用 autoload 方法。
*/
public static function register() {
// 注册自动载入函数,当尝试实例化一个未定义的类时,将调用此函数
spl_autoload_register(array(new self, 'autoload'));
}
/**
* 根据类名载入所在文件
*
* @param string $className 类名
*/
public static function autoload($className) {
// 获取命名空间前缀的长度
$namespacePrefixStrlen = strlen(self::NAMESPACE_PREFIX);
// 检查类名是否以命名空间前缀开头
if (strncmp(self::NAMESPACE_PREFIX, $className, $namespacePrefixStrlen) === 0) {
// 将类名转换为小写
$className = strtolower($className);
// 将命名空间分隔符转换为目录分隔符
$filePath = str_replace('\\', DIRECTORY_SEPARATOR, substr($className, $namespacePrefixStrlen));
// 构建文件路径
$filePath = realpath(__DIR__ . (empty($filePath) ? '' : DIRECTORY_SEPARATOR) . $filePath . '.lib.php');
// 如果文件存在,则加载文件
if (file_exists($filePath)) {
require_once $filePath;
} else {
// 如果文件不存在,输出文件路径(用于调试)
echo $filePath;
}
}
}
}