Using getters and setters
At first glance, it would seemingly make sense to define classes with public
properties, which can then be directly read or written. It is considered a best practice, however, to make properties protected
, and to then define a getter and setter for each. As the name implies, a getter retrieves the value of a property. A setter is used to set the value.
Tip
Best practice
Define properties as protected
to prevent accidental outside access. Use public
get* and set* methods to provide access to these properties. In this manner, not only can you more precisely control access, but you can also make formatting and data type changes to the properties while getting and setting them.
How to do it...
Getters and setters provide additional flexibility when getting or setting values. You are able to add an additional layer of logic if needed, something which would not be possible if you were to directly read or write a public property. All you need to do is to create a public method...