This article mainly introduces the automatic loading operation of the php class. It analyzes the functions and implementation techniques related to the automatic loading operation of the php class in detail in the form of examples. Friends in need can refer to the following
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 the class file, but the program will When a class is needed, it is automatically "dynamically loaded".
① When creating an object new
② Directly use a class name (operate static properties and methods)
Use the autoload magic function
When two situations occur, this function will be called, This function requires us to pre-define it and write the general statement for loading the class file
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 functions of the functions are the same as autoload(), but you can deal with 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'; } }
The above is the detailed content of How to understand the automatic loading operation of php classes. For more information, please follow other related articles on the PHP Chinese website!