详解spl_autoload_register()函数

12 篇文章 0 订阅
前言

该函数是一个自动加载函数,如果当我们实例化一个未定义类的时候,就会触发。现在基本上好多主流的框架都使用了延迟加载技术,例如YiiTp等等。所以我们也需要了解一下。

__autoload()

因为 spl_autoload_register() 是在 __autoload() 的基础上进行封装的,所以我们首先先看一下这个函数。

Man.class.php
<?php
class Man{
    public function getInfo(){
        echo 'hello world';
    }
}
?>
__autoload.php
<?php
// 延迟加载
function __autoload($class){
    $file = "./" . $class .'.class.php';
    if(file_exists($file)){
        require $file;
    }
}
$man = new Man();
$man->getInfo(); // hello world
?>

结果会输出"hello world",在实例化Man对象时,程序在本文件内并没有找到该对象,所以就会加载__autoload($class)这个函数,$class参数就是实例化的类名。

该方法的好处就是,可以避免引用过多的文件,使程序更加灵活。

spl_autoload_regsiter

接下来我们开始步入正题。

spl_autoload_regsiter.php
<?php 
function getClass($class){
    $file = "./" . $class . ".class.php";
    if(file_exists($file)){
        require $file;
    }
}
spl_autoload_register("getClass");
$man = new Man();
$man->getInfo();
?>

同样也会输出"hello world",但是这里因为spl_autoload_register("getClass")里面的参数值是getClass,所以程序会找这个方法,然后就跟__autoload方法一样了。

<?php
// 注意类里面必须是静态方法
class MyClass{
    public static function getClass($class){
        $file = "./" . $class . ".class.php";
        if(file_exists($file)){
            require $file;
        }
    }
}
// spl_autoload_register(['MyClass','getClass']);
spl_autoload_register("MyClass::getClass");
$man = new Man();
$man->getInfo();
?>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值