There are two ways to load PHP automatically.
The first scheme uses __autoload, the function is simpler and weaker.
However, one problem is not solved, that is, before the include to determine the existence of the problem of the file.
12345678910111213 |
set_include_path(
‘aa‘
. PATH_SEPARATOR . get_include_path());
function
__autoload(
$className
)
{
//如果加这个检测, 因为此文件不在当前目录下,它就会检测不到文件存在,
//但include是能成功的
if
(
file_exists
(
$className
.
‘.php‘
)) {
include_once
(
$className
.
‘.php‘
);
}
else
{
exit
(
‘no file‘
);
}
}
$a
=
new
Acls();
|
The second scenario is automatically loaded with SPL, which is specifically stated here.
Spl_autoload_register ()
A simple example
12345678910111213 |
set_include_path ( ' AA ' < Code class= "PHP plain". 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 () in the path to find the ". PHP" program with a lowercase file name. The default lookup extension also has ". Ini" and can also be used with the Spl_autoload_ Extenstions () registers the extension.
You can also find a function by defining your own functions in the case of a clear condition that cannot be found.
Such as
function Loader1 ($class)
{
Write some code to load yourself
}
function Loader2 ($class)
{
When Loader1 () was not found, I came to find
}
Spl_autoload_register (' Loader1 ');
Spl_autoload_register (' Loader2 ');
You can have more ...
How the MVC framework implements automatic loading
Set the 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 ']);
After obtaining the URL, parse out the controller and method.
Then set the auto load
123456789101112131415161718 |
class
Loader
{
/**
* 自动加载类
* @param $class 类名
*/
public
static
function
autoload(
$class
)
{
$path
=
‘‘
;
$path =
str_replace
(
‘_‘
,
‘/‘
,
$class
) .
‘.php‘
;
include_once
(
$path
);
}
} /**
* sql自动加载
*/
spl_autoload_register(
array
(
‘Loader‘
,
‘autoload‘
));
|
Route, instantiate the controller, call the method, and the thing you write begins to execute.
12345678910111213141516 |
/**
* 路由
*/
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‘
);
}
|
PHP Automatic loading