在Codeigniter中,get_instance()
是一个全局可用的函数,它返回Controler超对象,其中包含所有当前加载的类(它返回Controler类实例)。我将包含当前的源代码:
在Codeigniter.php
中定义了get_instance()
// Load the base controller class
require BASEPATH.'core/Controller.php';
function &get_instance()
{
return CI_Controller::get_instance();
}
CI_Controller
是在Controller.php
中定义的
class CI_Controller {
private static $instance;
/**
* Constructor
*/
public function __construct()
{
self::$instance =& $this;
// Assign all the class objects that were instantiated by the
// bootstrap file (CodeIgniter.php) to local class variables
// so that CI can run as one big super object.
foreach (is_loaded() as $var => $class)
{
$this->$var =& load_class($class);
}
$this->load =& load_class('Loader', 'core');
$this->load->set_base_classes()->ci_autoloader();
log_message('debug', "Controller Class Initialized");
}
public static function &get_instance()
{
return self::$instance;
}
}
下面是如何在user guide for creating libraries中使用它的推荐方法
利用库中的CodeIgniter资源
要在库中访问CodeIgniter的本机资源,请使用get_instance()
函数。此函数返回CodeIgniter超级对象。
通常,在控制器函数中,您将使用$this
结构调用任何可用的CodeIgniter函数:$this->load->helper('url'); $this->load->library('session'); $this->config->item('base_url');
等。
但是,$this
只能直接在控制器、模型或视图中工作。如果你想在你自己的自定义类中使用CodeIgniter的类,你可以这样做:
首先,将CodeIgniter对象赋给一个变量:
$CI =& get_instance();
将对象赋给一个变量后,您将使用该变量而不是$this
:$CI =& get_instance();$CI->load->helper('url');$CI->load->library(‘$this
’);$CI->config->item('base_url');等等。
注意:您会注意到上面的get_instance()
函数是通过引用传递的:
$CI =& get_instance();
这一点非常重要。引用赋值允许你使用原始的CodeIgniter对象,而不是创建它的副本。
相关帖子:explain $CI =& get_instance(); / Codeigniter: Get Instance
所以,这是我的实际问题:
为什么用户指南建议将get_instance()
赋值给变量?我相当肯定我理解不通过引用赋值的含义,但是为什么在get_instance()->load->model()
运行良好的情况下建议将其赋值给变量呢?
我在CI中看到许多用户定义的或第三方类,它们分配给对象的属性:
class MY_Class {
private $CI;
function __construct()
{
$this->CI =& get_instance();
}
function my_func()
{
$this->CI->load->view('some_view');
}
function my_other_func()
{
$this->CI->load->model('some_model');
}
}
可怜的例子,但我经常看到这种情况。为什么要麻烦这个方法,而不是直接调用get_instance()
呢?将整个Controller对象赋给一个类变量似乎不是一个好主意,即使它是一个引用。也许这无关紧要。
我想为get_instance()
编写一个包装器函数,以便它更容易输入,并且不必不断地将其赋给变量。
function CI()
{
return get_instance();
}
或者:
function CI()
{
$CI =& get_instance();
return $CI;
}
这样我就可以在任何地方使用CI()->class->method()
,而不需要麻烦地将它赋给一个变量,它非常容易编写和理解它的作用,并且可以产生更短、更优雅的代码。
CI()
函数之间有什么区别吗?get_instance()
赋值给变量而不是调用它?< &
>d39>中的代码是指定义它的位置吗?我对references的用途略知一二,并在适当的时候使用它们,但我从来没有见过一个函数以这种方式定义。如果我真的写了一个包装器函数,我也应该使用这个吗?请注意,这不是一个风格的问题,而是一个技术问题。我想知道使用我建议的方法是否有任何性能或其他方面的问题。
编辑:到目前为止,我们有:
是否还有其他问题,或者这些是唯一的潜在问题?
发布于 2011-08-26 02:48:10
据我所知,这是一个最方便的问题。您可能会在库中大量使用CI超对象,因此为什么不将其赋给一个变量,使其更易于使用呢?
还有一些其他的事情需要考虑。
get_instance()
,而不是将其结果存储在variable.发布于 2011-08-26 02:48:12
为什么建议将get_instance()赋值给变量,而不是直接调用它?
最有可能的是,建议保持与php4的向后兼容性,在默认情况下,对象不是通过引用传递的,而是被克隆的。
有什么理由不采用这种方法吗?
仅当您希望您的应用程序在过时的php安装上运行时。
发布于 2011-08-26 03:10:22
PHP4
和CI
最近放弃了对PHP4
的支持(从2.0.0
版本开始),因此不支持方法链接。而且,每次编写$CI
都比编写get_instance()
容易。
https://stackoverflow.com/questions/7195544
复制相似问题