Multiple classes in Codeigniter

I want to create an array of objects, so I did this to create a library, but I cannot figure out how to actually dynamically create instances in a loop and store each instance in an array. Can someone tell me please?

+4
source share
3 answers

By design, loading the CodeIgniter library can be done only once. Subsequent attempts to load the same library are ignored. You can (in some way) get around this by telling CI to create an instance of the class with a different name each time you load another copy of the library (see the answer to this question )

The best solution is probably to create your class yourself, instead of using the CI library loading mechanism. This way you can create and store as many copies as possible.

EDIT: I suggest leaving the class in the library directory and just use PHP include () to make it available to your models / controllers where necessary.

Regarding accessing CodeIgniter from your class, you can do this using the following code:

$CI =& get_instance(); $CI->load->helper('url'); $CI->load->library('session'); $CI->config->item('base_url'); 

The get_instance () function returns a CodeIgniter super object, and after it is assigned to the $ CI variable, you can access any of the CI methods as if you were from a model or controller, except for using $ CI instead of $ this. See this link for more details.

+1
source

To create 100 objects, you just need to loop from 0 to 99, each time creating an object and storing it in an array.

 class Foo { ... } $fooArray = array(); for ($i = 0; $i < 100; $i++) { $fooArray[] = new Foo(); } 

I am not sure if this question is related to CodeIgniter. Don't you mention more?

+1
source

Please check this link: I think this is the best way to do this:

Creating an object from a class in Codeigniter

It uses Code Igniter code, but it allows you to use the β€œnew” word, like any other OOP application.

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1306631/


All Articles