When PHP is executed, if it is found that a class needs to be used (as long as it is any operation related to this class), at this time, the current script does not have the definition code of this class! Then PHP will automatically call a function named __autoload() at this time! And, when calling, a parameter will be passed to the function, which is the class name of the currently required class.
#自动加载 函数function __aotuload($class_name){ if(!file_exists("./".$class_name.".class.php")){ include "./".$class_name.".class.php"; }else{ die("系统错误,没有找到相关的类!"); } }
Generally, the system’s autoloading function is __autoload(). However, as the project expands, multiple autoloading functions may appear. For example, if an automatic loading function appears in the loaded file, the problem of duplicate function names will arise!
We don’t use the __autoload function at all, but register the user’s own autoloading function to avoid the above situation!
#注册其他的自动加载函数 解决自动加载函数重名问题function f1($class_name){ if(!file_exists("./".$class_name.".class.php")){ include "./".$class_name.".class.php"; }else{ die("系统错误,没有找到相关的类!"); } } spl_autoload_register('f1');
The following points need to be noted:
1. Registration must occur before a certain class is required!
2, You can register multiple automatic loading functions. Before the required class file is loaded successfully, it will be executed in the order of registration until it is found!
3. Once other autoloading functions are registered, the system's default __autoload function will become invalid!
At this time, if you want to continue to use the __autoload function, you must re-register it like other ordinary functions!
In object-oriented programming style, we usually encapsulate user-defined automatic loading functions into a class!
The syntax is:
spl_autoload_register(array('class name','method name'));
In addition, There is also a relatively simple form of registering static methods:
spl_autoload_register('class name::method name');
At this time, registration The steps are as follows:
1, First, instantiate an object
2, and then register it using spl_autoload_register(). At this time, the parameter form of the function is as follows:
spl_autoload_register( array(object variable, 'method name'));
#注册自动加载方法class Common { public static function autoload($class_name){ if(!file_exists("./".$class_name.".class.php")){ include "./".$class_name.".class.php"; }else{ die("系统错误,没有找到相关的类!"); } } } //spl_autoload_register("Common::autoload"); spl_autoload_register(array("Common","autoload"));
Related recommendations:
implementation code of PHP simple routing and class automatic loading function
Detailed explanation of automatic loading of PHP files autoloading
In-depth summary of PHP automatic loading
The above is the detailed content of PHP implements automatic loading of related functions. For more information, please follow other related articles on the PHP Chinese website!