PHP class automatic loading mechanism and PHP class loading mechanism
Php automatic loading:
Before php5, we need to use a class or class method, which must be included or require before it can be used. Every time we use a class, we need to write an include statement, which is troublesome.
The php author wants to make it simple. It is best to reference a class. If no include is included, the system can automatically find the class and introduce it automatically ~
So the :__ autoload () function came into being.
It is usually placed in the application entry class, such as discuz, and in class_core.php.
Let's give a simple example:
First case: The content in file A. php is as follows:
<? Php
Class {
Public function _ construct (){
Echo 'fff ';
}
}
?>
The content in file C. php is as follows:
<? Php
Function _ autoload ($ class)
{
$ File = $ class. '. php ';
If (is_file ($ file )){
Require_once ($ file );
}
}
$ A = new A (); // This will automatically call _ autoload to introduce the. php file.
?>
Case 2:Sometimes I want to customize autoload and a cooler name loader, C. php is changed to the following:
<? Php
Function loader ($ class)
{
$ File = $ class. '. php ';
If (is_file ($ file )){
Require_once ($ file );
}
}
Spl_autoload_register ('loader '); // register an automatic loading method to overwrite the original _ autoload
$ A = new ();
?>
Case 3: I want to use a class to manage automatic loading.
<? Php
Class Loader
{
Public static function loadClass ($ class)
{
$ File = $ class. '. php ';
If (is_file ($ file )){
Require_once ($ file );
}
}
}
Spl_autoload_register (array ('loader ', 'loadclass '));
$ A = new ();
?>
The current format is the best.
Generally, we place spl_autoload_register (*) In the portal script, which is referenced from the beginning. For example, the following discuz practice.
If (function_exist ('spl _ autoload_register ')){
Spl_autoload_register (array ('core', 'autoload'); // If php5 and above exist, register autoload in the Self-written core class as the auto-loaded function.
} Else {
Function _ autoload ($ class) {// if not, rewrite the native php function _ autoload to allow it to call its core function.
Return core: autoload ($ class );
}
}
This part is thrown at the beginning of the entrance file, which is naturally excellent ~
Reprinted: http://www.cnblogs.com/zhongyuan/p/3583201.html