What is the advantage of using a super object in the encoder

I studied code igniter. and I come across this super object.

The code igniter has a function that loads classes and stores them in an instance variable. Each time we need to include a new class or a previously loaded class, the code igniter first looks for it in the array of instances, and if it is not found, load it and include it in the instanc array.

My question is in the class, when can we turn on the class using the load_class function (since this function first looks in the insntance array, therefore, it reduces the overhead of including the same class again and again), so I need to declare a super object to include predefined or loading new classes.

When can we do it?

class CLASSNAME { function functionname() { $object = load_class(classname, location); $object->callfunction(); } } 

So why do we have to do this?

 class CLASSNAME { function functionname() { $superobject = & get_instance(); $superobject->classobject->function(); } } 

I just want to know the advantage of using a super object. Is it just to include all the predefined objects or something deeper and more useful that I could not understand.

Thanks in advance.

+4
source share
2 answers

In the example you specified (if you only need a link to the library) - there is no benefit. get_instance() is a more common (and documented) function, and load_class() is for internal use only.

A possible benefit is that get_instance() gives you access to everything that your controller has, if, for example, you want to check the property of the controller, call the model method, etc.

0
source

Sometimes you need to have a class and extend another class to inherit. Like this:

 class Car extends Garage { // properties and functions } 

But in Codeigniter you have to extend CI_Controller to load libraries, helpers, etc.

To use both (extending your own class when loading your own CodeIgniters resources) you can use a super object. Example:

 class Car extends Garage { protected $CI; // We'll use a constructor, as you can't directly call a function // from a property definition. public function __construct() { // Assign the CodeIgniter super-object $this->CI =& get_instance(); } public function foo() { $this->CI->load->helper('url'); redirect(); } public function bar() { $this->CI->config->item('base_url'); } } 

Look here :

In some cases, you can develop classes that exist separately from your controllers, but have the ability to use all the CodeIgniters resources. It is easily possible, as you will see.

0
source

All Articles