开发者

Codeigniter: Get Instance

开发者 https://www.devze.com 2022-12-30 05:13 出处:网络
What is the purpose of \"Get Instance\" in Code开发者_开发问答igniter? How would you explain this to a total beginner?Ok, so everything in CodeIgniter runs through the super-magic $this variable. This

What is the purpose of "Get Instance" in Code开发者_开发问答igniter? How would you explain this to a total beginner?


Ok, so everything in CodeIgniter runs through the super-magic $this variable. This only works for classes, as $this basically defines the current class.

Your controller is a class, so $this is there, allowing you to do $this->load->model('whatever');

In models, you are also using a class. It is slightly different here, as $this only contains useful stuff as you are extending from Model. Still, $this is still valid.

When you are using a helper or a library, you need to find that "instance" or $this equivalent.

$ci =& get_instance();

…makes $ci contain the exact same stuff/code/usefulness as $this, even though you are not in a class, or not in a class that inherits it.

That's an explanation for total beginners after 2 pints, so it's either wrong or about right. ;-)


It's an implementation of the singleton pattern. Essentially, there is only one instance of the class in question, which is designed to be accessible globally. The get_instance method is static and so provides a way of accessing the instance from anywhere in your code.

0

精彩评论

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