PHP 自动加载

在编写面向对象(OOP) 程序时,很多开发者为每个类新建一个 PHP 文件。 这会带来一个烦恼:每个脚本的开头,都需要包含(include)一个长长的列表(每个类都有个文件)。

 

从 PHP 5 中,可以使用 spl_autoload_register() 函数注册任意数量的自动加载器,当使用尚未被定义的类(class)和接口(interface)时自动去加载。

通过注册自动加载器,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。 

autoload 机制可以使得 PHP 程序可以在使用类时才自动包含类文件,而不是一开始就将所有的类文件 include 进来,这种机制也称为 lazy loading。

 

代码示例:

a.php

<?php
class A {
    public function __construct() {
        echo "class A<br>";
    }
}

 

b.php

<?php
class B {
    public function __construct() {
        echo "class B<br>";
    }
}

 

index.php

<?php
spl_autoload_register(function ($class) {
    require __DIR__ . '/' . $class . '.php';
});

$a = new A;
$b = new B;

自动加载就是我们在 new 一个 class 的时候,不需要手动去写 require 来导入这个 class.php 文件,程序自动帮我们加载导入进来。

 

SPL Autoload

SPL 是 Standard PHP Library (标准 PHP 库) 的缩写。它是 PHP5 引入的一个扩展库,其主要功能包括 autoload 机制的实现及包括各种 Iterator 接口或类。SPL Autoload 具体有几个函数:

spl_autoload_register:注册 _autoload () 函数
spl_autoload_unregister:注销已注册的函数
spl_autoload_functions:返回所有已注册的函数
spl_autoload_call:尝试所有已注册的函数来加载类
spl_autoload :_autoload () 的默认实现
spl_autoload_extionsions: 注册并返回 spl_autoload 函数使用的默认文件扩展名

 

自动加载功能的优点如下:

  • 使用类之前无需 include 或者 require。
  • 使用类的时候才会 require/include 文件,实现了 lazy loading,避免了 require/include 多余文件。
  • 无需考虑引入类的实际磁盘地址,实现了逻辑和实体文件的分离。

 

posted @ 2020-03-26 02:36  Ryan_zheng  阅读(239)  评论(0编辑  收藏  举报