PHP 自动加载类
phpserver side programmingprogramming更新于 2025/7/19 0:37:17
简介
为了使用在另一个 PHP 脚本中定义的类,我们可以将其与 include 或 require 语句合并。然而,PHP 的自动加载功能不需要这种显式的包含。相反,当使用一个类(例如声明其对象等)时,如果它已使用 spl_autoload_register() 函数注册,PHP 解析器会自动加载它。因此,可以注册任意数量的类。这样,PHP 解析器在抛出错误之前,有最后的机会加载类/接口。
语法
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
该类首次使用时,将从其对应的 .php 文件加载
自动加载示例
此示例展示了如何注册一个类以实现自动加载
示例
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new test1();
$obj2 = new test2();
echo "objects of test1 and test2 class created successfully";
?>
输出
这将产生以下结果。−
objects of test1 and test2 class created successfully
但是,如果未找到具有 clas 定义的相应 .php 文件,则会显示以下错误。
Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 4 PHP Fatal error: Uncaught Error: Class 'test10' not found
带有异常处理的自动加载
示例
<?php
spl_autoload_register(function($className) {
$file = $className . '.php';
if (file_exists($file)) {
echo "$file included
";
include $file;
} else {
throw new Exception("Unable to load $className.");
}
});
try {
$obj1 = new test1();
$obj2 = new test10();
} catch (Exception $e) {
echo $e->getMessage(), "
";
}
?>
输出
这将产生以下结果。−
Unable to load test1.

