开发者

$this keyword in view in CodeIgniter

开发者 https://www.devze.com 2023-04-01 19:42 出处:网络
I\'m trying to understand how $this->load->view() works inside of a view file in CodeIgniter. The core/Controller.php is calling core/Loader.php which then calls _ci_load() which in turn does a

I'm trying to understand how $this->load->view() works inside of a view file in CodeIgniter.

The core/Controller.php is calling core/Loader.php which then calls _ci_load() which in turn does an include('/path/to/view');

Shouldn't $this refer to the Loader class at that point? How is $this referring to the controller?

By my understanding, you should have to call $this->view() inside of a view file. Not $this->load->view() because the load() function is not accessible insi开发者_如何学编程de of the Loader. It's a class variable of the Controller base class. i.e, $this->load =& load_class('Loader');

Please note: I'm trying to understand the CodeIgniter internals. I know perfectly well how to embed view files in other view files as a CodeIgniter user. Please do not leave answers explaining how to use $this->load().


To simplify the understanding of what $this refers to in a view, since a view is "loaded" by a controller method, the view is still run in the same scope as that method, meaning $this can have a different context depending on which class loaded it.

For example:

class Controller1 extends CI_Controller {}

In any view file loaded in this example controller, $this refers specifically to the Controller1 class, which can access CI_Controller public and protected properties/methods as well (like the Loader or Input classes, which are assigned to the load and input properties of CI_Controller) since it extends that class.

Controllers are still just plain old PHP classes. If I were to do this:

class Controller1 extends CI_Controller {
    $this->foobar = 'Hello';
}
class Controller2 extends CI_Controller {
    $this->foobar = 'World';
}

...if we load the same view file in any method of either of these controllers, using $this->foobar in that view file will return a different value.


Last time I checked, $this was of class CI_Loader, try var_dump($this); inside a view.


Check out:

https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Controller.php

is_loaded(); returns an array with the already loaded classnames and their aliases from the main container.

$this->load is then an instance of CI_Loader inside the controller.


Check:

https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Loader.php

Line 778

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号