如何在CodeIgniter中使用$this访问所有内容


How everything can be access using $this in CodeIgniter?

我是CodeIgniter的新手,只是通过CodeIgnitor框架和文档进行webt。但我不明白为什么所有的东西都可以使用keywork$this访问。我的意思是,如果我在构造函数中加载库或助手,请使用this->load->library();

在哪里可以找到名为"load"的类/函数,以及如何使用"$this"访问它。

只是想了解一下这个MVC框架是如何实现的。

使用变量$this访问类的方法。例如:

class foo {
public function hello(){
    print "hello";
}
public function using_hello()
{
    $this->hello();
}
}

换句话说,当您使用$this->load->library时,可能有一个名为load的方法,而里面有另一个方法,比如library。

我想,事情不是这么简单,但这就是想法。

所有控制器都扩展了主CI_Controller,因此调用类似$this->load的东西意味着访问父类CI_Coontroller内的父方法load()

$this->ci之所以有效,是因为使用$this->ci = &get_instance(),您正在调用对主控制器类的引用。。。再一次如果您在引导文件(IIRC.或codeigner.php文件)中查看,则会发现函数get_instance(),它只返回(通过引用)CI_Controller类的实例。

因此,基本上,调用$this->ci->load和$this->load是完全相同的事情,只是第一个在Controller/Model/View中是不必要的,因为系统已经在父类中(通过方法load)这样做了。

例如,如果你看一下库,你会发现使用$this->ci->method()是必要的,因为你需要拥有CI_Controller的所有方法,这是一种驱动整个框架的"超级类"。

看看loader类和CodeIgniter类,了解CI内部是如何工作的。请查看此链接了解更多信息:http://ellislab.com/codeigniter/user-guide/

基本上,index.php文件加载/system/core/CodeIgniter.php。它设置了一些变量,如$EXT$BM$OUT

稍后,当发出请求时,这就是驻留在/system/core/Controller.php:中的内容

class CI_Controller {
    public function __construct()
    {
        (...)
        // 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);
        }
        (...)
    }

这意味着在CodeIgniter.php中初始化的变量被加载到控制器内部(例如$DB变成$this->db等等),因此您只能通过编写$this->something来使用大部分内容。