How to create multiple instances of a library class in CodeIgniter?

I would like to create several instances of the class in CodeIgniter. I created my class as a library, but I cannot figure out which syntax to use to create multiple instances.

+4
source share
3 answers

In the CodeIgniter User Guide:

CI User Guide: Loader Class

Assigning a library to a different object name

If the third (optional) parameter is empty, the library will usually be assigned to the object with the same name as the library. For example, if the library is called Session, it will be assigned to a variable named $ This-> session.

If you prefer to set your own class names, you can pass your value to the third parameter: $ this-> load-> library ('session', '', 'My_session');

// Session class is now available with:

$ this-> my_session

I think what you are looking for.

+14
source

I know that this tread has long passed, but it was one of the questions that I met, looking for my answer. So here is my solution ...

This is PHP. Create your class as a library, load it using the standard CI loader class, but use it as in a regular PHP script.

Create your class:

class My_class { var $number; public function __construct($given_number){ $number = $given_number; } public function set_new_num($given_number){ $number = $given_number; } } 

Download it:

 // This will load the code so PHP can create an instance of the class $this->load->library('My_class'); 

Then create an instance and use the necessary object:

 $num = new My_class(24); echo $num->number; // OUTPUT: 24 $num->set_new_num(12); echo $num->number; // OUTPUT: 12 

The only time I use $ this-> my_class is to make calls to the static functions that I encode.

+8
source

Sorry to restore this topic, but I think I might have something reasonable.

You can do this to add multiple instances of the class. I don’t know if this violates the standard use of codeigniter anyway, but it looks more like codeigniter-ish than loading a library (which creates $ this-> library_name which is not used) and then makes 2 MORE instances with the keyword "new "

 $this->load->library( 'my_library', '', 'instance1' ); $this->load->library( 'my_library', '', 'instance2' ); $this->instance1->my_class_variable = 1; $this->instance2->my_class_variable = 2; echo $this->instance1->my_class_variable; // outputs 1 echo $this->instance2->my_class_variable; // outputs 2 

I use this in my code to create different menus. I have a β€œmenu” class and different instances for each menu, each of which has different menu items.

+4
source

All Articles