PHP supports two automatic loading methods.
The first scheme uses _ autoload, which is relatively simple and weak.
But there is a problem that cannot be solved, that is, to determine whether the file exists before include.
CopyCode The Code is as follows: set_include_path ('A'. path_separator. get_include_path ());
Function _ autoload ($ classname)
{
// If this check is added, because the file is not in the current directory, it will not detect the file,
// But the include operation is successful.
If (file_exists ($ classname. '. php ')){
Include_once ($ classname. '. php ');
} Else {
Exit ('no file ');
}
}
$ A = new ACLs ();
The second method is to use SPL for automatic loading.
Spl_autoload_register ()
A simple exampleCopy codeThe Code is as follows: set_include_path ('A'. path_separator. get_include_path ());
// Function _ autoload ($ classname)
//{
// If (file_exists ($ classname. '. php ')){
// Include_once ($ classname. '. php ');
//} Else {
// Exit ('no file ');
//}
//}
Spl_autoload_register ();
$ A = new ACLs ();
Spl_autoload_register () will automatically call spl_autoload () to find ". php" with lower-case file names in the path" Program By default, the extension ". ini" is found. You can also use spl_autoload_extenstions () to register the extension.
You can also use your own defined functions to find the missing conditions.
For example
Function loader1 ($ class)
{
// Write some loaded code by yourself
}
Function loader2 ($ class)
{
// When loader1 () cannot be found, I will come
}
Spl_autoload_register ('loader1 ');
Spl_autoload_register ('loader2 ');
More ........
How does the MVC Framework implement automatic loading?
First, set the path
'Include '=> array ('application/CATALOG/controllers', 'application/CATALOG/models',), $ include = array ('application/controllers ', 'application/models', 'application/library ');
Set_include_path (get_include_path (). path_separator. implode (path_separator, $ config ['include ']);
After obtaining the URL, parse the controller and method.
Then set automatic loading Copy code The Code is as follows: Class Loader
{
/**
* Automatically load classes
* @ Param $ class name
*/
Public static function autoload ($ class)
{
$ Path = '';
$ Path = str_replace ('_', '/', $ class). '. php ';
Include_once ($ PATH );
}
}
/**
* Automatic SQL Loading
*/
Spl_autoload_register (Array ('loader ', 'autoload '));
Route, instantiate the controller, call the method, and execute what you write.Copy codeThe Code is as follows :/**
* Routing
*/
Public Function Route ()
{
If (class_exists ($ this-> getcontroller ())){
$ Rc = new reflectionclass ($ this-> getcontroller ());
If ($ RC-> hasmethod ($ this-> getaction ())){
$ Controller = $ RC-> newinstance ();
$ Method = $ RC-> getmethod ($ this-> getaction ());
$ Method-> invoke ($ Controller );
} Else
Throw new exception ('No Action ');
} Else
Throw new exception ('no controller ');
}
The initial automatic loading is complete.