CI框架load_class方法分析
load_class 这个方法是一个实现了注册模式的典型方法
参数分析
它可以传入3个参数,类名,类的存放地址,实例化时候需要传入的参数
1.设置静态变量
static $_classes = array();
设置静态变量为一个数组,用来存放已经全部实例化过的类,static只会初始化一次,而且这个变量只会在当前函数中存在
2.检测实例化
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
}
是否已实例化,如果实例化了,就直接返回已经实例化的对象
3.检测需要加载的类的文件是否存在
$name = FALSE;
// Look for the class first in the local application/libraries folder
// then in the native system/libraries folder
foreach (array(APPPATH, BASEPATH) as $path)
{
if (file_exists($path.$directory.'/'.$class.'.php'))
{
$name = 'CI_'.$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once($path.$directory.'/'.$class.'.php');
}
break;
}
}
// Is the request a class extension? If so we load it too
if (file_exists(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php'))
{
$name = config_item('subclass_prefix').$class;
if (class_exists($name, FALSE) === FALSE)
{
require_once(APPPATH.$directory.'/'.$name.'.php');
}
}
// Did we find the class?
if ($name === FALSE)
{
// Note: We use exit() rather than show_error() in order to avoid a
// self-referencing loop with the Exceptions class
set_status_header(503);
echo 'Unable to locate the specified class: '.$class.'.php';
exit(5); // EXIT_UNK_CLASS
}
第一个foreach优先加载系统CI前缀的类文件
第二个才是加载自己扩展的类文件
4.实例化对象
is_loaded($class); // 存储到已实例化的类名的静态变量中
$_classes[$class] = isset($param)
? new $name($param)
: new $name();
return $_classes[$class];