tags:

views:

74

answers:

2

When is the right time to use functions to set variables inside of my models, verse simply directly assigning them?

AKA...

When do I use:

$model->set('status','active');

...instead of:

$model->status = 'active';
+2  A: 

using getters and setters is good for the encapsulation of code. It's always a good idea to use them.

Think about this:

  • What if your model has some variables that you don't want to be able to be read or changed (or both)?
  • What if you ever need to do something besides just getting and setting the variable? (for example, sanatizing data)?
GSto
Encapsulation also is extremely useful when debugging. Using getters and setters lets you track changes to variables easily and in only one place, rather than having to find everywhere in you code that you called $model->variable
eCaroth
ah, i see...that definitely makes sense:)
johnnietheblack
@eCarloth - yes, another good point.
GSto
A: 

If you're using a recent version of PHP (5.x), you can get the best of both worlds with the magic methods __get() and __set(). (PHP reference). Any access to an undefined property will be routed to the appropriate get/set function automatically.

I must admin that I'm not certain if this is really a good idea to use or not, but it seems like a decent fit for a base model class in a MVC system.

MadCoder