PHP类自动装载(PSR-4规范 简单版本)
教学案例分享,PHP5.3以上带命名空间,如何做类的自动装载,采用PSR-4规范的简单版本。
如果需要多条 autoload 函数,spl_autoload_register() 满足了此类需求。 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。
test.php
<?php
// src目录中,使用PSR-4命名规范的类,使用时将被自动装载
// PSR-4: 命名空间与目录对应,文件名采用"类名.php"格式,目录和文件名严格区分大小写
require_once './src/autoload.php';
var_dump(new Bar);
var_dump(new Demo\Foo);
var_dump(new Demo\Test\Baz);
use Demo\Test\Baz;
var_dump(new Baz);
src/autoload.php
<?php
/**
* 注册类自动装载函数 PSR-4规范 简单版本
* @author 邹义良
*/
spl_autoload_register(function ($class) {
// 兼容 PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
// 将类名转换为路径
$path = strtr($class, '\\', DIRECTORY_SEPARATOR);
// 拼接完整文件名
$file = __DIR__ . DIRECTORY_SEPARATOR . $path . '.php';
// 检测文件是否存在
if (file_exists($file)) {
include $file;
}
});