There are two ways to automate the download of PHP.
The first scheme uses __autoload, the function is simpler and weaker.
However, there is a problem that is not resolved, that is, before the include to determine whether the file exists.
Copy Code code as follows:
Set_include_path (' AA '. Path_separator. Get_include_path ());
function __autoload ($className)
{
If this test is added, because the file is not in the current directory, it will not detect the existence of the file.
But include can be successful.
if (File_exists ($className. '. php ')} {
Include_once ($className. '. php ');
} else {
Exit (' no file ');
}
}
$a = new Acls ();
The second scheme is automatically loaded with SPL, which is specifically mentioned here.
Spl_autoload_register ()
A simple example
Copy Code code as follows:
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 () automatically calls Spl_autoload () to find the ". PHP" program in the path with the lowercase file name. The extension for the default lookup is also ". Ini", and you can also use the Spl_autoload_ Extenstions () registers the extension.
In the case of not found in the clear, you can also define the function to find
Such as
function Loader1 ($class)
{
Write yourself some loaded code
}
function Loader2 ($class)
{
When Loader1 () can't find it, I'll find it.
}
Spl_autoload_register (' Loader1 ');
Spl_autoload_register (' Loader2 ');
It can be more ...
How the MVC framework implements automatic loading
Set Path First
' 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 ']);
In obtaining the URL, the controller and method are parsed.
Then set the auto load
Copy Code code as follows:
Class Loader
{
/**
* Auto Load Class
* @param $class 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 '));
Routing, instantiating a controller, invoking a method, you write something that begins to execute
Copy Code code 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.