0
0
PhpConceptBeginner · 3 min read

Getter and Setter in PHP: What They Are and How to Use Them

In PHP, getter and setter are special methods used to read and write private or protected object properties safely. They allow controlled access to these properties by defining how values are retrieved or changed.
⚙️

How It Works

Imagine you have a box with a lock. You don't want anyone to open it directly, but you want to let trusted people put things in or take things out. In PHP, private or protected properties are like that locked box. You can't access them directly from outside the object.

Getters and setters are like the trusted people who have the key. A getter is a method that lets you safely look inside the box (read a property), and a setter is a method that lets you safely put something inside or change what's inside (write a property). This way, you control how the property is accessed or changed, for example by checking values or formatting data.

💻

Example

This example shows a simple class with private properties and getter and setter methods to access them.

php
<?php
class Person {
    private string $name;
    private int $age;

    public function getName(): string {
        return $this->name;
    }

    public function setName(string $name): void {
        $this->name = $name;
    }

    public function getAge(): int {
        return $this->age;
    }

    public function setAge(int $age): void {
        if ($age >= 0) {
            $this->age = $age;
        } else {
            echo "Age cannot be negative.";
        }
    }
}

$person = new Person();
$person->setName("Alice");
$person->setAge(30);
echo "Name: " . $person->getName() . "\n";
echo "Age: " . $person->getAge() . "\n";
Output
Name: Alice Age: 30
🎯

When to Use

Use getters and setters when you want to protect your object's data from being changed directly. This is important when you need to validate data before saving it or when you want to hide the internal details of how data is stored.

For example, if you have a user profile, you might want to check that the age is not negative or that a name is not empty before saving it. Getters and setters help keep your code safe and easier to maintain.

Key Points

  • Getters retrieve the value of private or protected properties.
  • Setters allow controlled modification of these properties.
  • They help enforce rules like validation or formatting.
  • Using them improves code safety and encapsulation.

Key Takeaways

Getters and setters control access to private or protected properties in PHP classes.
They allow you to add validation or processing when reading or writing data.
Using them helps keep your code safe and easier to maintain.
Always use setters to protect your object’s internal state from invalid changes.