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.
Copy codeThe 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 example
Copy 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 "program. the default search extension is ". ini ", you can also use spl_autoload_extenstions () to register an 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 codeThe 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.