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];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值