4

I want to create an array of objects, so what I did was to create a library but I can't figure out how to actually dynamically create instances of it in a loop and store each instance in an array. Can anyone tell me please?

Leon
  • 43
  • 1
  • 3

2 Answers2

1

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

class Foo { ... }

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

I'm not sure what this question has to do with CodeIgniter. Is there more you're not mentioning?

Samir Talwar
  • 14,220
  • 3
  • 41
  • 65
  • I already know how to create an object in php. However, as far as I know, you don't just create classes in CI but instead libraries and then load theme like so: $this->load->library('libraryName'); This line creates an instance of libraryName and stores it in a variable called libraryName. Instead of that, I would like it to return that instance so I can store it in an array. Thanks. – Leon Apr 11 '10 at 20:59
  • 4
    From what I understand, CodeIgniter's not really object-oriented. Each library is a singleton, and multiple calls just get the same instance. This is by design, and I don't believe there's a clean way to go around it. The best way, as far as I know, would be to `require` the library file and instantiate it yourself, rather than use `$this->load->library`. – Samir Talwar Apr 12 '10 at 11:10
1

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

A better solution is probably to create your class yourself, instead of using CI's library loading mechanism. That way you can create and store as many copies as you need.

EDIT: I'd suggest leaving the class in the libraries directory, and just using PHP's include() to make it available to your models/controllers where needed.

As for accessing CodeIgniter from within your class, you can do it 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 the CodeIgniter super object, and once it's assigned to the $CI variable, you can access any of CI's methods just like you would from within a model or controller, except using $CI instead of $this. See this link for more information.

Community
  • 1
  • 1
Eric G
  • 4,018
  • 4
  • 20
  • 23
  • Great, I like this solution - however, where do I store my class, physically and how do I include it in a model or a view for example. Also I would like to use Ci's classes and libraries from with in this class, Would that be possible? Thanks! – Leon Apr 12 '10 at 08:11