In PHP, getters and setters are special methods used to access and modify the private or protected properties of a class. They are part of the encapsulation concept in object-oriented programming, which restricts direct access to class variables and ensures data integrity.
In PHP, class properties can be declared as private
or protected
to prevent them from being accessed directly from outside the class. Getters and setters provide controlled access:
class Person {
private $name;
public function getName() {
return $this->name;
}
public function setName($name) {
if (is_string($name) && strlen($name) > 0) {
$this->name = $name;
} else {
throw new Exception("Invalid name");
}
}
}
$person = new Person();
$person->setName("Alice");
echo $person->getName(); // Outputs: Alice
In this example, $name
is a private property. The getName()
method is the getter, and setName()
is the setter. The setter includes basic validation before assigning the value.
In modern PHP (especially PHP 8+), you can also use features like property promotion and readonly properties to simplify code, but getters and setters remain fundamental for complex logic or validation.