Concept
How can getters and setters validate values before changing private variables?
ComputerScienceOne / Accessor & Mutator Methods
"One advantage to using getters and setters (as opposed to naively making everything public) is that you can have greater control over the values that your variables can take. For example, we may want to do some data validation by rejecting null values or invalid values. For example:\n\n1 public function setFirstName($firstName) {\n\n2 if($firstName === null) {\n\n3 throw new Exception(\"names cannot be null\");\n\n4 } else {\n\n5 $this->firstName = $firstName;\n\n6 }\n\n7 }\n\n8\n\n9 public function setGpa($gpa) {\n\n10 if($gpa < 0.0 || $gpa > 4.0) {"
Related Ideas
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods
- How do accessor and mutator methods use this to access instance variables?ComputerScienceOne · Accessor & Mutator Methods
- How do member methods differ from static methods?ComputerScienceOne · Accessor & Mutator Methods
- What is covered in section 34.2.1, Accessor & Mutator Methods?ComputerScienceOne · Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- Where is section 45.2.1, Accessor & Mutator Methods, located?ComputerScienceOne · Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .