Getters return the value of a property. They may also make a small modification of the returned result.
Let's look the following example:
Output:
Members that have __
prefix are meant to be accessed only inside the class body.
If we need to access it outside the class body a getter needs to be defined.
Basically get_side
accesses the private member __side
.
Accessing a private member (__side
in this case) won't throw exception
but it's a good coding convention private members to be accessed only inside the class body.
Setters allow for a property to be modified. They are important since they can provide validation before a value is set.
Together getters and setters can control access and modification of a class member.
Let's look at the following example:
Output:
Explanation:
__age
is a private member (because it has __
prefix)
so it's supposed to be accessed / modified via it's getters and setters.obj1
a value of 20 is set for the __age
property via it's setter - set_age
.obj2
a value of -10 is attempted to be set for the __age
property. Due to the validation at line 6
a value of 0 is set.Because private members can have validation before modification (setter) and controlled access (getter).
It seems easier to have only public members (without __
prefix). This way there is no need for getters
and setters. It's a better practice to have private members that are
accessed with getter and modified through setter. This way a validation can be
provided in a setter and the public access can be done only to some members -
those which have getters.