Possible Duplicate:
Is it really that wrong not using setters and getters?
Why use getters and setters?
I have been always wondering why are people using getters/setters in PHP instead of using public properties?
From another question, I’ve copied this code:
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
I see no difference between this and using public fields.
Well, I know it may help us to validate data in both getter and setter, but the example above just doesn’t fit it
Getters and setters are used in order to prevent code outwith the class from accessing implementation details. Maybe today some piece of data is just a string, but tomorrow it has be created by joining two other strings together and also keeping a count of the number of times the string is retrieved (OK, contrived example).
The point is that by forcing access to your class to go through methods, you’re free to change how your class does things without impacting other code. Public properties don’t give you that guarantee.
On the flip side, if all you want to do is hold data, then public properties are fine, but I think that’s a special case.