View Full Version : which one to use and why ??

07-03-2007, 12:57 PM
Hello forums!!
I am curious about some question which i am going to mention here.
we know the advantage of using getters and setters in OOP.
Let us consider the case:

class className{
var prop1;
var prop2;
var prop3;

function className(){
// Empty constructor

function setProp1($prop1){
$this->prop1 = $prop1;
function getProp1(){
return $this->prop1;
function setProp2($prop2){
$this->prop2 = $prop2;
function getProp2(){
return $this->prop2;
function addProp12(){
$value = $this->prop1 + $this->prop2;
// Alt $value = $this->getProp1() + $this->getProp2();
return $value;

// Using Class
$classObj = new className();
echo $classObj->addprop12();
My Question is very simple..
once the property is set using methods, for internal use in the class file
which one to use and why ?
1> $value = $this->prop1 + $this->prop2;
2> $value = $this->getProp1() + $this->getProp2();

Thanks in advance to all of you.

ralph l mayo
07-03-2007, 02:24 PM
I always use setter methods instead of public data in case I need to add validation to enforce restrictions on what values a given datum can have.

Even if at the outset I don't care what $foo is, if I find out later something catastrophic happens when it is 0 I can add the validation to the setter without changing any client code. If I'm using public data I have to track down all the places I set that field (if that's even possible) and make sure I'm following the new protocol in each instance, or at least add a redundant check to ever method in my class that uses that datum. That could be an ugly maintenance scenario.

That said I think using 'var' is the same as saying 'public' so it doesn't really matter: if you use var your interface is not mandatory. Use public/private/protected instead as appropriate.