当一个项目需要根据不同的请求载入不同的类的时候,之前的做法是require不同的文件进来,但是如果数量巨大就没办法一个语句一个语句去写,而且如果有不小心误删的文件,就会导致PHP FATAL ERROR。在php5.2之后,我们使用__autoload()方法来自动加载类,但是这个方式后来也不好。比如在一个项目中我引入了三个框架,每个框架都有一个autoload,这样的话会报一个函数名重复的错误。
不过在php5.4版本以后,标准php库提供了一个方法,解决了这些问题:spl_autoload_register()
使用方法如下:
index.php
<span style="font-size:14px;"><?php
spl_autoload_register('autoloadIndex');
t1::test();
t2::test();
function autoloadIndex($class)
{
require __DIR__."/".$class.".php";
}</span>
t1.php
<span style="font-size:14px;"><?php
class T1 {
public function __construct()
{
}
public function test()
{
echo __FILE__;
}
}</span>
<span style="font-size:14px;"><?php
class T2 {
public function __construct()
{
}
public function test()
{
echo __FILE__;
}
}</span>