php自动加载类的方法

php自动加载类的方法

废弃的函数:__autoload():

test.class.php:

<?php
class test{
	public function index(){
		return "index";
	}
}
?>

 demo.php实例化这个类:

<?php
function __autoload($class){
	require $class.'.class.php';
}
$a = new test();
echo $a->index();  //index
?>

原理就是每当实例化一个类是php文件会自动查找调用__autoload()方法,这个方法在高版本php中已被废弃

spl_autoload_register()函数:

第一种传值方式:

demo.php:

<?php
spl_autoload_register('auto');  //传入函数名
$a = new test();
echo $a->index();
function auto($class){
	require $class.'.class.php';
}
?>

当实例化一个类时会自动调用spl_autoload_register()函数,此函数根据传入的函数规则进行查找类文件,支持数组形式传值

第二种传值方式:(数组形式,数组里是类名和静态方法)

<?php
class load{
	public static function auto($class){    //必须是静态方法
		require $class.'.class.php';
	}
}
spl_autoload_register(array('load','auto'));  //类名,方法
$a = new test();
echo $a->index();     //index
?>

第三种传值方式(匿名函数)

demo.php:

<?php
spl_autoload_register(function ($class){
		require $class.'.class.php';
	});
$a = new test();
echo $a->index();  //index
?>

PS:spl_autoload_register()函数有三个参数,第一个就是要注册的函数,第二个当无法注册时是否抛出异常true,第三个如果是true这个函数会添加到队列之首

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值