Php is automatically loaded. php is automatically loaded in two ways.
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.
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, // 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
set_include_path('aa' . 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
Class Loader {/*** automatic loading class * @ param $ class name */public static function autoload ($ class) {$ path = ''; $ path = str_replace ('_', '/', $ class ). '. php'; include_once ($ path) ;}}/*** SQL auto load */spl_autoload_register (array ('loader ', 'autoload '));
Route, instantiate the controller, call the method, and execute what you write.
/*** Route */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.