Master PHP Getters and Setters: Practical Examples and Best Practices

This article explains the purpose, usage, and advantages of PHP getters and setters, provides clear code examples for both, and demonstrates a combined implementation that validates and secures private properties, helping developers write more robust and maintainable code.

php Courses
php Courses
php Courses
Master PHP Getters and Setters: Practical Examples and Best Practices

Getters in PHP

Purpose

A getter is a method that runs filtering or processing logic when a private property is read, ensuring the retrieved value is valid and consistent.

Usage

class MyData {
    private $name;

    public function getName() {
        // optional validation or transformation
        return $this->name;
    }
}

Advantages

Fine‑grained control over property access.

Prevents direct manipulation of private fields.

Improves data consistency and object reliability.

Setters in PHP

Purpose

A setter processes a value before assigning it to a private property, guaranteeing that the new value meets required criteria.

Usage

class MyData {
    private $name;

    public function setName($value) {
        // optional validation or transformation
        $this->name = $value;
    }
}

Advantages

Enables validation and transformation of incoming data.

Prevents unsafe direct assignments.

Maintains consistency and stability of object state.

Combined Example

The following class demonstrates how getters and setters work together to enforce validation rules for a user's name and age.

class User {
    private $name;
    private $age;

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

    public function setName($value) {
        if (strlen($value) < 3) {
            throw new Exception("Username must be at least 3 characters");
        }
        $this->name = $value;
    }

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

    public function setAge($value) {
        if ($value < 18 || $value > 60) {
            throw new Exception("Age must be between 18 and 60");
        }
        $this->age = $value;
    }
}

$user = new User();
$user->setName('Tom');   // set username
$user->setAge(25);       // set age

echo $user->getName();   // retrieve username
echo $user->getAge();    // retrieve age

In this example, setName() and setAge() validate inputs before assignment, while getName() and getAge() provide read‑only access to the validated data. This pattern guarantees that the object's internal state remains safe and consistent.

PHPOOPgettersetterdata encapsulation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.