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

 

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

转载于:https://www.cnblogs.com/norm/p/9114774.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值