>im试图理解CodeIgniter中的框架结构,我刚刚开始并提出了这个小误解。
所以有人可以在以下立场下帮助我:-
1-为什么他们使用引用来传递类的实例...我的意思是为什么不只是一个简单的变量?
2-为什么该函数将类的名称存储在数组中而不是"字符串变量"中(请不要判断我的php术语是最糟糕的)..... ?!
static $_classes = array();
^^^^^^^ this cloud be just ("") or am i missing something
这是函数,所以你不会去寻找它。
function &load_class($class, $directory = 'libraries', $prefix = 'CI_')
{
static $_classes = array();
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
}
$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 = $prefix.$class;
if (class_exists($name) === FALSE)
{
require($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)
{
require(APPPATH.$directory.'/'.config_item('subclass_prefix').$class.'.php');
}
}
// Did we find the class?
if ($name === FALSE)
{
// Note: We use exit() rather then show_error() in order to avoid a
// self-referencing loop with the Excptions class
exit('Unable to locate the specified class: '.$class.'.php');
}
// Keep track of what we just loaded
is_loaded($class);
$_classes[$class] = new $name();
return $_classes[$class];
}
键是 $_classes = array();
之前的 static
关键字。这使得$_classes
数组在对函数的多次调用之间保持其值。基本上,他们将其用作实例化类的本地缓存。为此,字符串将不起作用。
请参阅手册中有关 static 关键字的更多信息。
至于引用返回,我认为这是 php4 的包袱,直到 2.x 在 php4 上支持 CI。您可能会发现这篇博文有助于了解从 php4 到 php5 的更改。
传递
一个普通(非引用)变量"似乎"有效,因为每次传递它时,前一个实例都会被覆盖,最后一个或最新的实例取而代之。因此,每次创建新类实例时。但这是浪费,原因有两个......
它创建一个新的实例变量,而不取消设置前一个实例变量(尽管 PHP 最终会对这些变量进行垃圾回收),从而保持被某些恶意代码读取的风险,并在您必须付费的宝贵服务器空间中浪费几个字节。
实例表示状态。"输入"状态、"安全"状态、"配置"状态等。如果创建新变量,则会创建这些状态的副本。如果您偶然犯了任何错误,那么您在一个"输入"实例中保存的当前状态可能不会更改以反映当前或最新状态。假设另一个已经改变;如果您在不同的场合同时使用它们,那么可能会导致下一步的冲突和灾难。