Junior — Middle
In which cases are access methods used to obtain the value of an object's properties?
sobes.tech AI
Answer from AI
Access methods (getters and setters) are used to retrieve and set the values of an object's properties when it is necessary to control access to these properties. This is useful in the following cases:
- Properties are declared as
privateorprotectedto restrict direct access from outside the class. - You need to add logic when getting or changing the value (e.g., validation, transformation, caching).
- It is necessary to ensure encapsulation and data protection of the object.
Example in PHP:
class User {
private $name;
public function getName() {
return $this->name;
}
public function setName($name) {
if (strlen($name) > 0) {
$this->name = $name;
}
}
}
$user = new User();
$user->setName('Иван');
echo $user->getName(); // Иван
Thus, access methods allow controlling and protecting the internal state of the object.