php自动加载

php自动载方法有两种.

第一种方案用__autoload,这个函数较简单,也较弱.

但有一问题没有解决, 就是在include前判断文件是否存在的问题.

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();

第二种方案用spl自动加载,这里具体说一下这个.

spl_autoload_register()

一个简单的例子

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()会自动先调用spl_autoload()在路径中查找具有小写文件名的".php"程序.默认查找的扩展名还有".ini",还可以用spl_autoload_extenstions()注册扩展名.

在找不到的清况下,还可以通过自己定义函数查找

function loader1($class)

{

//自己写一些加载的代码

}

function loader2($class)

{

//当loader1()找不到时,我来找

}

spl_autoload_register('loader1');

spl_autoload_register('loader2');

还可以更多........

MVC框架是如何实现自动加载的

首先设置路径

    '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']));

在获取URL,解析出控制器与方法.

然后设置自动加载

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'));
路由,实例化控制器,调用方法,你写的东西就开始执行了
    /**
     * 路由
     */
    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');
    }

初步的自动加载就完成了
原文地址:https://www.cnblogs.com/yuxing/p/1760742.html