PHP自动加载类

介绍

为了使用在另一个PHP脚本中定义的类,我们可以将其与include或require语句合并。但是,PHP的自动加载功能不需要这种明确的包含。相反,如果使用类(用于声明其对象等),则PHP解析器会自动加载该类(如果已使用spl_autoload_register()函数注册。因此可以注册任何数量的类。这样,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\n";
      include $file;
   } else {
      throw new Exception("Unable to load $className.");
   }
});
try {
   $obj1 = new test1();
   $obj2 = new test10();
} catch (Exception $e) {
   echo $e->getMessage(), "\n";
}
?>

输出结果

这将产生以下结果。-

Unable to load test1.