时间:2021-07-01 10:21:17 帮助过:9人阅读
类的自动加载
在外面的页面中,并不需要去引入类文件,但程序会在需要一个类的时候自动去“动态加载”该类。
① 创建一个对象的时候new
② 直接使用一个类名(操作静态属性与方法)
使用__autoload魔术函数
当出现两种情况时候,就会调用该函数,该函数需要我们预先定义,在其中写好加载类文件的通用语句
- function __autoload($name){
- require './lib/'.$name.'.class.php';
- }
使用spl_autoload_register()
用它注册(声明)多个可以代替__autoload()作用的函数,自然也得去定义这些函数,并且函数的作用跟__autoload()作用一样,不过此时可以应对更多的情形
- //注册用于自动加载的函数
- spl_autoload_register("model");
- spl_autoload_register("controll");
- //分别定义两个函数
- function model($name){
- $file = './model/'.$name.'.class.php';
- if(file_exists($file)){
- require './model/'.$name.'.class.php';
- }
- }
- //如果需要一个类,但当前页面还没加载该类
- //就会依次调用model()和controll(),直到找到该类文件加载,否则就报错
- function controll($name){
- $file = './controll/'.$name.'.class.php';
- if(file_exists($file)){
- require './controll/'.$name.'.class.php';
- }
- }
- //若注册的是方法而不是函数,则需要使用数组
- spl_autoload_register(
- //非静态方法
- array($this,'model'),
- //静态方法
- array(__CLASS__,'controller')
- );
项目场景应用
- //自动加载
- //控制器类 模型类 核心类
- //对于所有的类分为可以确定的类以及可以扩展的类
- spl_autoload_register('autoLoad');
- //先处理确定的框架核心类
- function autoLoad($name){
- //类名与类文件映射数组
- $framework_class_list = array(
- 'mySqldb' => './framework/mySqldb.class.php'
- );
- if(isset($framework_class_list[$name])){
- require $framework_class_list[$name];
- }elseif(substr($name,-10)=='Controller'){
- require './application/'.PLATFORM.'/controller/'.$name.'.class.php';
- }elseif(substr($name,-6)=='Modele'){
- require './application/'.PLATFORM.'/modele/'.$name.'.class.php';
- }
- }
希望本文所述对大家PHP程序设计有所帮助。
更多php类的自动加载操作实例详解相关文章请关注PHP中文网!