源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

php类的自动加载操作实例详解

  • 时间:2021-07-30 15:55 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:php类的自动加载操作实例详解
本文实例讲述了php类的自动加载操作。分享给大家供大家参考,具体如下: [b]类的自动加载[/b] 在外面的页面中,并不需要去引入类文件,但程序会在需要一个类的时候自动去“动态加载”该类。 ① 创建一个对象的时候new ② 直接使用一个类名(操作静态属性与方法) [b]使用__autoload魔术函数[/b] 当出现两种情况时候,就会调用该函数,该函数需要我们预先定义,在其中写好加载类文件的通用语句
function __autoload($name){
  require './lib/'.$name.'.class.php';
}

[b]使用spl_autoload_register()[/b] 用它注册(声明)多个可以代替__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')
);

[b]项目场景应用[/b]
//自动加载
//控制器类 模型类 核心类
//对于所有的类分为可以确定的类以及可以扩展的类
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相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/357.htm]PHP运算与运算符用法总结[/url]》、《[url=http://www.1sucai.cn/Special/495.htm]PHP网络编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部