What are Getters and Setters in PHP?

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.

Why Use Getters and Setters?

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:

Example:

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.

Benefits of Getters and Setters:

  1. Encapsulation – Protects internal state by preventing direct access.
  2. Validation – Ensures that only valid data is assigned to properties.
  3. Flexibility – Logic can be changed without modifying external code using the class.
  4. Debugging and Logging – You can add logging or breakpoints inside these methods.

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.