当没有Composer 时PHP引入外部文件(自动加载的实现效果)
2021-12-24 08:32:56

当没有自动加载(Composer)的时候引入外部文件 autoload 实现自动加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
function classLoader($class)
{
// DIRECTORY_SEPARATOR 为 ‘/’ 正则替换 把 命名空间 \\ 替换 /
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
// realpath 返回绝对路径 调整文件夹返回
$file = realpath(__DIR__ .'/../../'. DIRECTORY_SEPARATOR . $path . '.php');
// 是否为文件,引入 。
if (file_exists($file)) {
require_once $file;
}
}
// 添加注册
spl_autoload_register('classLoader');