Setters and Getters
Let's discuss the use of setters and getters in packages in this lesson.
We'll cover the following...
Setters
In order to assign a value to a member variable of an object after it has been instantiated, we define a setter. Let’s implement setter methods for the package Shape to set the name and sides of the shape.
Explanation
In the above code snippet, setName and setSides are setter methods for the package Shape.
-
In lines 21-25, the
$valuevariable is used to assign a value to the member variablename. This is essentially done in the line$self->{name} = $value;. -
In line 38, this setter is called with the argument
Triangleto set the name of the$squareobject to Triangle. -
Similarly, in lines 27-31, the
$valuevariable is used to assign a value to the member variablesides. This is essentially done in the line$self->{sides} = $value;. -
In line 39, this setter is called with the argument
3to set the sides of the$squareobject to 3.
Getters
In order to retrieve the value from a member variable of an object, we define a getter. Let’s implement getter methods for the package Shape to get the name and sides of the shape.
Explanation
In the above code snippet, getName and getSides are getter methods for the shape package.
-
In lines 33-36, the line
return $self->{name};returns the name of our object. -
This getter is then called in the line 47, and the value returned is stored in the variable
$shapeName. -
Similarly, in lines 38-41, the line
return $self->{sides};returns the sides of our object. -
In line 48, this getter is called, and the value returned is stored in the variable
$shapeSides.