php自动加载类的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/84451913

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这个函数会添加到队列之首

猜你喜欢

转载自blog.csdn.net/qq_41179401/article/details/84451913