This article mainly introduces the php class automatic loading operation, and analyzes in detail the functions and implementation skills related to the php class automatic loading operation in combination with the instance form, for more information about php automatic loading, see the following example. We will share this with you for your reference. The details are as follows:
Automatic loading of classes
On the external page, you do not need to introduce class files, but the program will automatically "dynamically load" the class when it needs a class.
① New when creating an object
② Use a class name directly (operate static attributes and methods)
Use the _ autoload magic function
This function will be called in two cases. this function needs to be pre-defined to write general statements for loading class files.
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 functions the same as _ autoload, however, in this case, we can deal with more situations.
// Register the function spl_autoload_register ("model") for automatic loading; spl_autoload_register ("controll"); // define two function models ($ name) {$ file = 'respectively '. /model /'. $ name. '. class. php '; if (file_exists ($ file) {require '. /model /'. $ name. '. class. php ';} // if a class is required, but the current page does not load the class. // model () and controll () are called in sequence until the class file is found to be loaded, otherwise, function controll ($ name) {$ file = '. /controll /'. $ name. '. class. php '; if (file_exists ($ file) {require '. /controll /'. $ name. '. class. php ';}}
// If you are registering a method rather than a function, you need to use the array spl_autoload_register (// non-static method array ($ this, 'model '), // static method array (_ CLASS __, 'controller '));
Project scenario application
// Automatically load // controller class model class core class // it can be a deterministic class for all classes and an extensible class spl_autoload_register ('autoload '); // first process the determined framework core class function autoLoad ($ name) {// class name and class file ing array $ 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 you with PHP programming.
For more details about php auto-loading operation instances, refer to PHP Chinese network!