• php自动加载


    当实例化一个不存在的类的时候,PHP会尝试去加载它。比如目录下有一个test的类,它保存在test.php中。在index中,如果没有包含test.php进来,那么实例化test类的时候便会调用__autoload尝试将test类加载进来。

    test.php

    <?php

    class test{

      public fucntion index(){

        echo "hello word";

      }

    }

    index.php

    <?php

    header('Content-Type:text/html;charset=urf-8');

    function __autoload($class){

      echo '你正在尝试加载' . $class;

      require $class . '.php';

    }

    new test();

    运行结果会输出你正在尝试加载test,并且不会出现任何的问题。另外自动加载函数的参数 $class 是实例化类的类名。

    spl_autoload_register()  - 注册给定函数作为 __autoload 的实现

    官方解释:

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

    参数:

    autoload_function      欲注册的自动装载函数。如果没有提供任何参数,则自动注册 autoload 的默认实现函数spl_autoload()

    throw   此参数设置了 autoload_function 无法成功注册时, spl_autoload_register()是否抛出异常。

    prepend  如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。

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

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

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

     

    那么什么是spl_autoload、spl_auto_load_call呢? 官方解释:

    spl_autoload  -  __autoload()函数的默认实现

    是什么意思呢? 当不使用任何参数调用spl_autoload_register()函数,那么在以后进行自动加载的时候回默认调用这个函数,个人理解是给autoload函数队列里面添加了一个默认的函数,那么这个函数怎么使用呢

    spl_autoload ( string $class_name [, string $file_extensions ] ) : void      (相信熟悉PHP手册的人都会看懂的)

    下面来解释一下参数:

    class_name   类名

    file_extensions    在默认情况下,本函数先将类名转换成小写,再在小写的类名后加上 .inc 或 .php 的扩展名作为文件名,然后在所有的包含路径(include paths)中检查是否存在该文件。

     

    spl_autoload_call ( string $class_name ) : void  — 尝试调用所有已注册的__autoload()函数来装载请求类,  可以直接在程序中手动调用此函数来使用所有已注册的__autoload函数装载类或接口。

    参数   :  calss_name    搜索的类名

    下面给出一些使用示例,

    复制代码如下:

    <?php

    // function __autoload($class) {
    //     include 'classes/' . $class . '.class.php';
    // }

    function my_autoloader($class) {
        include 'classes/' . $class . '.class.php';
    }

    spl_autoload_register('my_autoloader');

    // 或者,自 PHP 5.3.0 起可以使用一个匿名函数
    spl_autoload_register(function ($class) {
        include 'classes/' . $class . '.class.php';
    });

    ?>

     

  • 相关阅读:
    0X03异常错误处理
    (组合数学)AtCoder Grand Contest 019 F
    (NTT)AtCoder Grand Contest 019 E
    (dp)AtCoder Grand Contest 019 D
    (dp)AtCoder Regular Contest 081 E
    (最小费用流)hdu 6118(2017百度之星初赛B 1005) 度度熊的交易计划
    (容斥)Codeforces Round #428 (Div. 2) D. Winter is here
    (最大团)Codeforces Round #428 (Div. 2) E. Mother of Dragons
    (FFT)HDU 6088(2017 多校第5场 1004)Rikka with Rock-paper-scissors
    近期部分题目汇总
  • 原文地址:https://www.cnblogs.com/skl-bobo/p/10444245.html
Copyright © 2020-2023  润新知