Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Is there no way to use models as objects in a more traditional manner?, but without hacking the CI 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.

Any insight into the matter is greatly appreciated guys.

EDIT: thanks for the answers guys, i think that i missed a vital part of working the "Codigniter 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.

Once again - thanks for the help and answers.

like image 350
Dan Matthews Avatar asked Dec 05 '11 19:12

Dan Matthews


People also ask

Can you instantiate more than one instance of the same class in one program?

You can always create multiple instances of a class! This is what classes are designed for! Each object will hold its own individual inner variables (unless they are static, in which case they are shared).

Can there be more than one instance of an object?

Object and Object instances mean the same. If you would like to create multiple objects or mulriple instances, same thing, you need to call new as an array allocation, e.g. Show activity on this post. You cannot have "different objects of the same instance" because objects and instances are the same thing.


1 Answers

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 CI namespace. As you can see, it gets polluted really quickly if you try to use it for everything.

like image 139
minboost Avatar answered Oct 16 '22 11:10

minboost