Search code examples
phpoopcodeigniterobjectinstantiation

How can I instantiate multiple instances of the same object in CodeIgniter?


With traditional OOP, I would (or could, rather) create a model / object that represents a User, with properties that reflect that, i.e., name, id, job title, etc.

I could then create a new instance of that object and assign it to a variable, and if I was looping through a result set, I could create an instance for each one. With CodeIgniter, this seems impossible, as doing:

$this->load->model('User');

Instantiates it, and places it for use at $this->user.

Isn't there any way to use models as objects in a more traditional manner? But without hacking the CodeIgniter way of doing things?

I understand that you can assign things to a different object name using $this->load->model('User', 'fubar'), but it's not as dynamic as simply assigning an instance to a variable.


Thanks for the answers guys. I think that I missed a vital part of working the "CodeIgniter Way", but I've just been looking through a contributed library, and the practice of using the same instance (assigned to the CodeIgniter namespace), but clearing the instance variables after each use, seems to be a great way to work that removes my reservations.


Solution

  • You don't have to use the load() functions. You can just use require_once and new User(), like you normally would.

    Using the load() should only be for things you want in the global CodeIgniter namespace. As you can see, it gets polluted really quickly if you try to use it for everything.