Home  >  Article  >  Backend Development  >  Detailed explanation of automatic loading operation examples of PHP classes

Detailed explanation of automatic loading operation examples of PHP classes

高洛峰
高洛峰Original
2016-12-21 14:00:54925browse

The example in this article describes the automatic loading operation of the PHP class. Share it with everyone for your reference, the details are as follows:

Automatic loading of classes

In the external page, there is no need to introduce class files, but the program will automatically "dynamically load" the class when it needs it.

① When creating an object new

② directly use a class name (to operate static properties and methods)

Use the __autoload magic function

When two situations occur, this function will be called, and this function requires us Define in advance and write a general statement for loading class files in it

function __autoload($name){
  require './lib/'.$name.'.class.php';
}

Use spl_autoload_register()

Use it to register (declare) multiple functions that can replace __autoload(). Naturally, you have to define these functions. , and the function has the same function as __autoload(), but it can handle more situations at this time

//注册用于自动加载的函数
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')
);

Project scenario application

//自动加载
//控制器类 模型类 核心类
//对于所有的类分为可以确定的类以及可以扩展的类
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';
  }
}


I hope this article will help everyone in their PHP programming design help.

For more detailed examples of automatic loading operations of PHP classes, please pay attention to the PHP Chinese website for related articles!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn