I’m looking for advice/experience on using public variables vs private variables with accessor methods in php.
eg
$obj->foo = ‘a’;
echo $obj->foo;
vs
$obj->setFoo(‘a’);
echo $obj->getFoo();
What I like about public variables is the shorter syntax – just seems less work to use. I understand that it could make refactoring more difficult later, but I’ve never experienced it (meaning, sometimes the design changes – but usually the accessor methods would need to be changed any.)
The other option is to store the variables in an array and use magic methods (__get/__set) to access them – then I have the ease of use of public variables with the ability to refactor or accessor methods.
Any experience or references of what people do in the php world.
And for anyone that hold the accessor method are the best way, is there a valid need/use for public variables?
Yes, accessor methods are an overhead, although the syntax for using setters/getters is just as clean as direct access of public properties… slightly more wordy, but just as clean.
Biggest benefit of accessor methods is that you can use your set method to validate values and reject inappropriate values (e.g. trying to set a property that should always be an integer to a string or an array)… but this verification only works if external code can’t access the property directly.
Second benefit if your code has related properties, where a change to property A requires a change to property B as well… if the properties are public, you can’t control (or enforce) this.
Using set methods allows you to implement fluent interface, or to cleaner code for instances like:
instead of
if you include a return in your set method