什么是 PHP 中的自动加载类

为了使用在另一个 PHP 脚本中定义的类,我们可以将其与 include 或 request 语句合并。但是,PHP 的自动加载特性不需要这样明确的包含。相反,如果使用 spl_autoload_register ()函数注册了一个类(用于声明其对象等) ,PHP 解析器将自动加载该类。因此可以注册任意数量的类。这样,PHP 解析器在发出错误之前获得最后一次装入类/接口的机会。

语法

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

注意: 当这个类第一次使用时,它将从相应的.php文件中加载。

自动加载

示例1: 这个示例显示了一个类是如何注册用于自动加载的

<?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(test1.php): failed to open stream:
 No such file or directory in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 3
Warning: include(): Failed opening ‘test1.php’ for inclusion (include_path=’.:/usr/local/lib/php’) 
in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 3
Fatal error: Uncaught Error: Class ‘test1’ not found in
 /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php:5
Stack trace:
#0 {main}
thrown in /home/guest/sandbox/5efa1ebc-c366-4134-8ca9-9028c8308c9b.php on line 5

使用异常处理自动加载

<?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.
© 版权声明
THE END
喜欢就支持一下吧
点赞0打赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容