类的自动加载

含义:
当某行代码需要一个类的时候,php的内部机制可以做到“自动加载该类文件”,以满足该行需要一个类的这种需求。
什么时候需要一个类?
1,new一个对象的时候;
2,使用一个类的静态方法的时候;
3,定义一个类(B)并以另一个类(A)作为父类的时候;
在这里插入图片描述
条件和要求
1, 当需要一个类的时候,就会自动调用某个函数(默认是__autoload),并传入所需要的类的名字
2, 一个类应该保存到一个独立的“类文件中”:即其中只有该类的定义,没有别的代码;
3,习惯上,类文件的命名要有一定的“规则”,通常是:类名.class.php
4,通常,我们需要将各种类,存储在一些特定的目录中,以方便确定其位置!
5,在该自动加载的函数中,“充分”使用传过来的类名,以构建一个合适的文件路径并载入;
在这里插入图片描述
自定义自动加载函数:
刚才,__autoload()函数,是系统内部的自动加载函数,我们只是定义其函数体。
但:
我们可以使用更多函数(自定义的),来实现更灵活的自动加载!
基本模式为:
spl_autoload_register(“函数1”); //声明“函数1”作为自动加载函数;
spl_autoload_register(“函数2”); //声明“函数2”也作为自动加载函数;

然后,就去定义这些函数,跟定义__autoload()函数一样:
function 函数1( $class_name ){
//…
}
function 函数2( $class_name ){
//…
}

这样,系统就会一次调用这些自动加载函数去加载所需要的类,直到加载成功!
在这里插入图片描述
这里用到了以前学到的知识,如果require则不会往下继续执行下面的代码
另外,有时候遇到了这样的情况
设我们有一个类文件A.php里面定义了一个名字为A的类:

<?php   
class A{   
	public function __construct(){   
		echo 'Got it.';   
	}   
}

然后我们有一个index.php需要用到这个类A,常规的写法就是

<?php   
require('A.php');   
$a = new A();

但是有一个问题就是,假如我们的index.php需要包含的不只是类A,而是需要很多类,这样子就必须写很多行require语句,有时候也会让人觉得不爽。

在上面那个例子中,index.php可以这样写

function __autoload($class){   
	$file = $class . '.php';   
	if (is_file($file)) {   
		require_once($file);   
	}   
}   
$a = new A();

上面只是最简单的示范,__autoload只是去include_path寻找类文件并加载,我们可以根据自己的需要定义__autoload加载类的规则,也可以使用spl_autoload_register来注册我们自己的autoload函数.

function loader($class){   
	$file = $class . '.php';   
	if (is_file($file)) {   
		require_once($file);   
	}   
}   
spl_autoload_register('loader');   
$a = new A();

比较重点的一个是调用php中某个类的某个方法,这个时候往spl_autoload_register中增加的参数为数组,数组的第一个参数是类的名字,第二个参数是类的方法名字

class Loader{   
	public static function loadClass($class){   
		$file = $class . '.php';   
		if (is_file($file)) {   
			require_once($file);   
		}   
	}   
}   
spl_autoload_register(array('Loader', 'loadClass')); //参数为数组,数组的第一个参数是类的名字,第二个参数是类的方法名字  
$a = new A();

<?php 
class Framework{
	private static function autoload(){
		$array=array(__CLASS__,'load');
		spl_autoload_register($array);
	}
	private static function load($classname){
		if(substr($classname.-10)=='Controller'){
			include CUR_CONTROLLER_PATH.$classname.'.class.php';
		}elseif(substr($classname,-5)=='Model'){
			include MODEL_PATH.$classname.'.class.php';
		}else{

		}
	}
}

<?php 
class Framework{
	private static function autoload(){
		$array=array($this,'load');
		spl_autoload_register($array);
	}
	private static function load($classname){
		if(substr($classname.-10)=='Controller'){
			include CUR_CONTROLLER_PATH.$classname.'.class.php';
		}elseif(substr($classname,-5)=='Model'){
			include MODEL_PATH.$classname.'.class.php';
		}else{

		}
	}
}

这两种,一种是调用类中静态方法,一种是调用对象中的方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值