Master PHP Getters and Setters: Practical Examples and Best Practices

This guide explains PHP getters and setters, detailing their purpose, implementation, and advantages, and provides comprehensive code examples that demonstrate how to validate and control access to private properties for safer, more reliable object-oriented programming.

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

Getters: Purpose and Usage

Purpose

Getters are special methods that run when a private property is read. They allow filtering, validation, or transformation of the value before it is returned, ensuring the data is reasonable and complete.

Implementation

In PHP a getter method name starts with get followed by the property name. Example:

class MyData {
    private $name;

    public function getName() {
        // custom filtering or processing logic
        return $this->name;
    }
}

Advantages

Fine‑grained control over property access.

Prevents direct exposure of private data.

Improves code safety, consistency, and reliability.

Setters: Purpose and Usage

Purpose

Setters are special methods that run when a private property is assigned a value. They enable filtering, validation, or transformation before the value is stored, guaranteeing the assigned data is sensible.

Implementation

In PHP a setter method name starts with set followed by the property name. Example:

class MyData {
    private $name;

    public function setName($value) {
        // custom filtering or processing logic
        $this->name = $value;
    }
}

Advantages

Controlled and filtered assignment of properties.

Avoids direct writes to private fields, enhancing safety.

Ensures data consistency and stability for externally used objects.

Combined Use of Getters and Setters

A complete example demonstrates both getters and setters with validation logic for a User class:

class User {
    private $name;
    private $age;

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

    public function setName($value) {
        if (strlen($value) < 3) {
            throw new Exception("用户名长度不能少于3个字符");
        }
        $this->name = $value;
    }

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

    public function setAge($value) {
        if ($value < 18 || $value > 60) {
            throw new Exception("年龄必须在18到60之间");
        }
        $this->age = $value;
    }
}

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

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

The User class defines two private properties, $name and $age, each with a getter and a setter. The setters enforce that the name must be at least three characters long and that the age must be between 18 and 60, guaranteeing data integrity.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Object-Orienteddata validationgettersetter
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.