spl_autoload_register()函数

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

__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();
?>

 

posted @ 2016-08-23 01:25  伊人世界  阅读(199)  评论(0编辑  收藏  举报
Fork me on GitHub