php的命名空间与自动加载实现方法(4)
接着我们在创建一个加载类(不需要命名空间),它处于 目录中:
class Loader
{
/* 路径映射 */
public static $vendorMap = array(
'app' => __DIR__ . DIRECTORY_SEPARATOR . 'app',
);
/**
* 自动加载器
*/
public static function autoload($class)
{
$file = self::findFile($class);
if (file_exists($file)) {
self::includeFile($file);
}
}
/**
* 解析文件路径
*/
private static function findFile($class)
{
$vendor = substr($class, 0, strpos($class, '\\')); // 顶级命名空间
$vendorDir = self::$vendorMap[$vendor]; // 文件基目录
$filePath = substr($class, strlen($vendor)) . '.php'; // 文件相对路径
return strtr($vendorDir . $filePath, '\\', DIRECTORY_SEPARATOR); // 文件标准路径
}
/**
* 引入文件
*/
private static function includeFile($file)
{
if (is_file($file)) {
include $file;
}
}
}
最后,将 Loader 类中的 autoload 注册到 spl_autoload_register 函数中:
include 'Loader.php'; // 引入加载器
spl_autoload_register('Loader::autoload'); // 注册自动加载
new \app\mvc\view\home\Index(); // 实例化未引用的类
/**
* 输出: <h1> Welcome To Home </h1>
*/
示例中的代码其实就是 ThinkPHP 自动加载器源码的精简版,它是 ThinkPHP 5 能实现惰性加载的关键。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对黑区网络的支持。
