I personally try to avoid using setters and getters. If a public property needs to be protected from bad or out-of-range data, then it should probably be avoided. One important thing I’ve learnt in the last few months, is to program for the language you’re using. Because PHP, like most object-orientated languages, doesn’t have any getter or setter mechanisms built-in, I try to avoid the need for them in my code. On the other hand, a language like C# which does have a built-in getter and setter mechanism, lends itself to heavier use of object properties.
On the same note, PHP is also a dynamic language, so it’s good to use this to your advantage when it comes to setters and getters. For example, I don’t hesitate in making public boolean properties. Even though I can’t guarantee that this property want be set to a non-boolean value, I can rely on PHP’s dynamic type conversion in my code. For example, the following is perfectly safe, even though the variable I expect to be set to a boolean value, is actually an array…
$boolean = array("chalk", "cheese");
if($boolean == true)
{
// Do something
}
Some may argue that this approach could hide bugs. That could be considered a con to some people, but it’s important not to forget the pros of this approach, which is cleaner, simpler, less error-prone code. Programming is all about striking that balance, as I’m sure everyone would agree.
You can also take advantage of PHP’s inline type casting when your variable absolutely must be of a given type. E.g…
$string = 67.6;
if((string) $string === '67.6')
{
// Do something.
}
Not a very good example, but it demonstrates my point. Inline type casting like this should only be rarely required. If you’re code absolutely requires a variable to be a specific type or set of types, and a setter/getter is the only way you can think of achieving this, then this is normally an indicator that you should possibly rethink your class. It’s sometimes not possible to avoid setters and getters completely, but use more as a last resort, than a preferred solution.
That’s my opinion anyway. Good design in one language, may not always be good design in another, and vice versa.