php的自动加载函数spl_autoload_register和__autoload

spl_autoload_register和__autoload是用来自动加载类的,不用每次都require,include这样搞。

先说__autoload的用法,

在同级目录建立2个文件,一个index.php,一个是test.php,内容。

test.php
<?php class Test{ function sayhi(){ echo "hi"; } } ?>
index.php
<?php //第一种 function __autoload($class){ $file = $class.'.php'; if(is_file($file)){ require_once ($file); } } $o = new Test(); $o->sayhi(); ?>

 这样执行,在index.php找不到test类的时候,会自动执行__autoload函数,把test类加载进来,并且实例化,输出hi

接下来讲spl_autoload_register。也是上面那个test.php,index.php如下

function loadscript($class){
    $file = $class.'.php';

    if(is_file($file)){
        require_once ($file);
    }
}

spl_autoload_register('loadscript');


$o = new Test();
$o->sayhi();

这里注意下,找不到Test类之后,会去执行spl_autoload_register ,注册的函数loadscript,接着把test类加载进来。

同时,可以把loadscript函数写在类的静态方法中,这样也能自动加载

//第三
class m {
public static function loadprint( $class ) {
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
}

spl_autoload_register(array('m','loadprint'));
$o = new Test();
$o->sayhi();

自己参考上面写一遍都知道了~

猜你喜欢

转载自www.cnblogs.com/norm/p/9114774.html