In object-oriented programming, getters and setters (also known as accessors and mutators) are methods used to access and modify the values of private or protected class properties. Getters return the current value of a property, while setters modify its value.

Here’s an example of using getters and setters:
class Person {
private $name;
private $age;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getAge() {
return $this->age;
}
public function setAge($age) {
$this->age = $age;
}
}
$person = new Person();
$person->setName('John');
$person->setAge(30);
echo $person->getName(); // Output: John
echo $person->getAge(); // Output: 30
In this example, the Person
class has two private properties $name
and $age
. To access and modify these properties, the class provides two pairs of getter and setter methods: getName()
and setName()
for the $name
property, and getAge()
and setAge()
for the $age
property.
When the setName()
and setAge()
methods are called, they modify the values of the $name
and $age
properties, respectively. When the getName()
and getAge()
methods are called, they return the current values of these properties.
Using getters and setters has several benefits:
- Encapsulation: By making the properties private, the class ensures that their values can only be accessed and modified through the getter and setter methods. This helps to protect the properties from unauthorized access or modification.
- Validation: The setter methods can validate the values being set for the properties, ensuring that they meet certain requirements or constraints before they are accepted.
- Flexibility: The getter and setter methods can be customized to provide different levels of access or functionality for different properties. For example, a
getFullName()
method could combine the$firstName
and$lastName
properties to return a full name, while asetPassword()
method could encrypt the password value before setting it.