spl_autoload_register

1.函数详解
bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
如果需要多条 autoload 函数,spl_autoload_register() 满足了此类需求。 它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。

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

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

prepend
如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。*/
2.例子
//test1.php
namespace Test;
class test1{ public static function ceshi(){ echo __METHOD__; echo '</br>'; } }
//test2.php
namespace Test;
class test2{
    public static function ceshi(){
        echo __METHOD__; //返回类的名字和方法的名字
        echo '</br>';
    }
}
//index.php
spl_autoload_register('autoload_self');

Test\test1::ceshi();//调用静态方法格式-->命名空间名\类名::静态方法名

Test\Test2::ceshi();

function autoload_self($class){//定义引入文件函数
    //echo $class ===> Test\test1
    list($namespace,$fileName) = explode('\\',$class);
    require __DIR__.'\\'.$fileName.'.php';
}

输出

Test\test1::ceshi
Test\test2::ceshi

posted on 2018-11-15 17:45  running-fly  阅读(607)  评论(0编辑  收藏  举报

导航