• 初识 spl_autoload_register


    spl_autoload_register

    一、首先我们看来自官网的定义

    版本要求:php版本为5.1.2+

    说明:注册给定的函数作为__autoload的实现。即自动加载

    函数参数说明:

    bool spl_autoload_register([callable $autoload_function[,bool $throw=true[,bool $prepend=false]]])

    将函数注册到spl __autoload函数队列中,如果该队列中函数尚未激活,则激活他们。

    如果在你的程序中已经实现了 __autoload函数队列中,如果该队列中的函数尚未激活,则激活他们。

    如果在你的程序中已经实现了 __autoload函数,它必须显示注册到__autoload()队列中。因为spl_autoload_register()函数会将Zend Engine中的__autoload()函数取代为spl_autoload()或spl_autoload_call()

    如果需要多条autoload函数,spl_autoload_register()满足了此类需求,它实际上创建了autoload函数队列,按定义时的顺序逐个执行。相比之下__autoload()只可以定义一次。

    • 参数 autoload_function:预注册的自动装载函数,如果没有提供任何参数,则自动注册autoload的默认实现函数spl_autoload()
    • 参数throw:此参数设置了autoload_function无法成功注册时,spl_autoload_register()是否抛出异常
    • 参数 prepend:如果是true,spl_autoload_register()会添加函数到队列之首,而不是队列尾部

    返回值: 成功时返回true,失败时返回false.

    二、来自网络资料的汇总整理含义理解

     

    首先我们定义三个类文件如下示例

    <?php
    //test1.class.php
    class test1{
        public function __construct(){
            echo "test1
    ";
        }
    }
    ?>
    
    
    <?php
    //test2.class.php
    class test2{
        public function __construct(){
            echo "test1
    ";
        }
    }
    ?>
    
    
    <?php
    //test3.class.php
    class test3{
        public function __construct(){
            echo "test3
    ";
        }
    }
    ?>

    普通情况下我们引入这三个类文件,要写三个include/require/include_once/require_once

    如果使用__autoload()

    我们这么做

    function __autoload($classname){
        $filename = "./class/".$classname.".class.php";
        if(is_file($filename)){
            include $filename;
        }
    }


    如果使用spl_autoload_register

    我们这么做

     
    
    function loadclass($classname){
        $filename = "./class/".$classname.".class.php";
        if(is_file($filename)){
            include $filename;
        }
    }
    // spl_autoload_register()函数让这个loadclass具备了自动加载类的功能
    spl_autoload_register("loadclass");


    注:SPL是Standard PHP Library(标准PHP库)的缩写。它是PHP5引入的一个扩展库,其主要功能包括autoload机制的实现及包括各种Iterator接口或类。SPL autoload机制的实现是通过将函数指针autoload_func指向自己实现的具有自动装载功能的函数来实现的。SPL有两个不同的函数spl_autoload, spl_autoload_call,通过将autoload_func指向这两个不同的函数地址来实现不同的自动加载机制。 

    推荐阅读:

    spl_autoload_register()函数的作用

    spl_autoload_register 函数详解

    PHP函数spl_autoload_register()用法和__autoload()介绍

  • 相关阅读:
    .net中实现运行时从字符串动态创建对象
    C# 用 VB.net 函數庫 實現全角與半角轉換
    實現.net 加載插件方式
    VS2008下載
    Lotus Notes Send EMail from VB or VBA
    用C#写vs插件中的一些Tip
    SQL2005中异常处理消息框可直接使用
    C#路径/文件/目录/I/O常见操作汇总
    利用.net反射动态调用指定程序集的中的方法
    说说今年的计划
  • 原文地址:https://www.cnblogs.com/ddddemo/p/5623573.html
Copyright © 2020-2023  润新知