The thing that's weird is that you have a setter, but are leaving the property public
. (Assuming there's no __get
magic going on.)
You usually want to use getters/setters to get more control over what can be assigned to a property and what can't. Or, you may want to execute code when the property is accessed or changed. In either case, you should force the use of the getters/setters by making the property private
or protected
, otherwise it's pretty pointless. It's about preventing yourself or others that will use the class from shooting their own foot.
If the setter in your example only sets the value without doing anything else, it's superfluous. If it does do something else that is required whenever the value is set, you have a flaw in your class design since it's possible to change the value without using the setter.
class Foo {
public $bar = 0; // is only allowed to contain numeric values
public function setBar($val) {
if (is_numeric($val)) {
$this->bar = $val;
}
}
}
$obj = new Foo();
$obj->bar = 'some value'; // set a string, which is not allowed
If you'd make $bar
protected
, that wouldn't be possible.