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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
< ? 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注册自动载入函数
*/
public static function register () {
// 注册自动载入函数,当尝试实例化一个未定义的类时,将调用此函数
spl_autoload_register ( array ( new self , 'autoload' ));
}
/**
* 根据类名载入所在文件
* @param $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 ;
}
}
}
}
命名空间声明: namespace LaneWeChat ; 定义了类的命名空间, 表明这个类属于LaneWeChat模块。
类定义: class Autoloader 定义了一个用于自动加载类文件的类。
常量定义: const NAMESPACE_PREFIX = 'LaneWeChat\\' ; 定义了命名空间前缀,用于识别类名。
register方法: 注册自动载入函数, 当尝试实例化一个未定义的类时, 将调用 autoload 方法。
autoload方法: 根据类名载入所在文件。检查类名是否以命名空间前缀开头, 如果是, 则构建文件路径并加载文件。如果文件不存在, 则输出文件路径。