PHP 类自动加载
简介
要使用在其他 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
但是,如果没有找到具有类定义的相应 .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.
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP