Concept
How do accessor and mutator methods provide access to private member variables?
ComputerScienceOne / Accessor & Mutator Methods
"Since we have made all the member variables private, no code outside the class may access or modify their values. It is generally good practice to make member variables private to restrict access. However, if we still want code outside the object to access or mutate (that is, change) the variable values, we can define accessor and mutator methods (or simply getter and setter methods) to facilitate this. Each getter method returns the value of the instance’s variable while each setter method takes a value and sets the instance’s variable to the new value. It is common to name each getter/setter by prefixing a get and set to the variable’s name using lower camel casing. For example:\n\n1 public function getFirstName() {\n\n2 return $this->firstName;\n\n3 }\n\n4\n\n5 public function setFirstName($firstName) {\n\n6 $this->firstName = $firstName;\n\n7 }"
Related Ideas
- How do accessor and mutator methods use this to access instance variables?ComputerScienceOne · Accessor & Mutator Methods
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods
- How does PHP visibility protect class data?ComputerScienceOne · Data Visibility
- How does encapsulation group and protect related data?ComputerScienceOne · Encapsulation & Objects
- Why are getters, setters, and immutable member variables useful?ComputerScienceOne · Constructors
- How do you use Java instances and invoke their methods?ComputerScienceOne · Usage
- What are the visibility levels used to protect Java data?ComputerScienceOne · Data Visibility
- How can PHP reference a member variable dynamically?ComputerScienceOne · Accessor & Mutator Methods