解释$ CI =&get_instance();

Hai*_*ood 84 php codeigniter

浏览codeigniter的源代码,

在它的帮助函数中,我一直看到代码 $CI =& get_instance(); ,任何人都可以向我解释这段代码是如何工作的?

我得到它返回对$ CI超级对象的引用,但是它get_instance()来自哪里?

irc*_*ell 72

它基本上是一个使用函数而不是静态方法的单例设计模式.

要深入了解,请查看源代码

所以基本上,它不强制执行单例,但它是公共函数的快捷方式......

编辑:其实,现在我明白了.对于PHP4兼容性,他们必须执行双全局变量hack才能使其正确返回引用.否则引用将全部搞砸.而且由于PHP4不支持静态方法(好吧,无论如何都适用),使用该函数是更好的方法.所以它仍然存在由于遗留原因......

因此,如果您的应用程序仅为PHP5,那么相反应该没有任何问题CI_Base::get_instance();,它是相同的......

  • 什么时候使用CI超级对象?你能指点我一些关于CI超级对象的CI文档吗? (2认同)

Wad*_*ade 19

get_instance()是CodeIgniter的核心文件中定义的函数.当您位于超级对象之外的范围内时,可以使用它来获取对CodeIgniter超级对象的单例引用.

我很确定它是在base.php或类似的东西中定义的.


小智 8

只有扩展 CI_Controller,Model,View 的类可以使用

$this->load->library('something');
$this->load->helper('something');//..etc
Run Code Online (Sandbox Code Playgroud)

您的自定义类不能使用上述代码。要在自定义类中使用上述功能,您必须使用

$CI=&get instance();
$CI->load->library('something');
$CI->load->helper('something');
Run Code Online (Sandbox Code Playgroud)

例如,在您的自定义类中

// this following code will not work
Class Car
{
   $this->load->library('something');
   $this->load->helper('something');
}

//this will work
Class Car
{
   $CI=&get_instance();
   $CI->load->library('something');
   $CI->load->helper('something');
}
// Here $CI is a variable.
Run Code Online (Sandbox Code Playgroud)