Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
Thread: which one to use and why ??
07-03-2007, 12:57 PM #1
- Join Date
- Dec 2005
- Thanked 0 Times in 0 Posts
which one to use and why ??
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:
// Empty constructor
$this->prop1 = $prop1;
$this->prop2 = $prop2;
$value = $this->prop1 + $this->prop2;
// Alt $value = $this->getProp1() + $this->getProp2();
// Using Class
$classObj = new className();
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.
07-03-2007, 02:24 PM #2
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.