Menu
Coddy logo textTech

Getters and Setters

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 40 of 91.

Now that you understand access modifiers, how do you safely interact with private properties from outside the class? The answer is getters and setters - public methods that provide controlled access to private data.

A getter retrieves a property's value, while a setter modifies it. This pattern lets you add validation or logic when data is accessed or changed:

<?php
class User {
    private string $email;
    private int $age;
    
    public function getEmail(): string {
        return $this->email;
    }
    
    public function setEmail(string $email): void {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->email = $email;
        }
    }
    
    public function getAge(): int {
        return $this->age;
    }
    
    public function setAge(int $age): void {
        if ($age >= 0 && $age <= 150) {
            $this->age = $age;
        }
    }
}

$user = new User();
$user->setEmail("john@example.com");
$user->setAge(25);

echo $user->getEmail() . "\n";
echo $user->getAge();

Output:

john@example.com
25

The setter validates the email format and ensures age is reasonable before storing the values. Without setters, anyone could assign invalid data directly. You can also create read-only properties by providing only a getter, or write-only properties with only a setter.

Key Point: Getters and setters give you control over how private data is accessed and modified, allowing validation, formatting, or any custom logic.

challenge icon

Challenge

Easy

Let's build a product inventory system that uses getters and setters to protect and validate product data. You'll create a Product class that ensures prices are always positive and stock quantities are never negative — demonstrating how setters can enforce business rules.

You'll organize your code across two files:

  • Product.php — Create a Product class with three private properties: $name (string), $price (float), and $stock (integer). Implement getters and setters for each property with the following validation rules:
    • setName() should only accept non-empty strings — if the string is empty after trimming, don't update the property
    • setPrice() should only accept values greater than 0 — reject zero or negative prices
    • setStock() should only accept values of 0 or greater — reject negative stock quantities
    Each getter should simply return the corresponding property value. Add a public method getInfo() that returns "[name]: $[price] ([stock] in stock)" with the price formatted to 2 decimal places.
  • main.php — Include the Product file. You'll receive four inputs: a product name, a price, a stock quantity, and a new price to update. Create a Product instance and use the setters to assign the initial name, price (converted to float), and stock (converted to integer). Print the result of getInfo(). Then attempt to update the price with the new price value (converted to float) and print getInfo() again. Finally, attempt to set the stock to -5 (an invalid value) and print getInfo() one more time to confirm the stock wasn't changed.

Your setters act as gatekeepers — they validate incoming data before allowing changes to the private properties. When invalid data is passed (like a negative stock), the setter simply ignores it, keeping the existing valid value intact. This is the power of encapsulation: your object maintains its integrity regardless of what external code tries to do.

Cheat sheet

Use getters and setters to provide controlled access to private properties. A getter retrieves a value, while a setter modifies it with optional validation:

<?php
class User {
    private string $email;
    private int $age;
    
    public function getEmail(): string {
        return $this->email;
    }
    
    public function setEmail(string $email): void {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->email = $email;
        }
    }
    
    public function getAge(): int {
        return $this->age;
    }
    
    public function setAge(int $age): void {
        if ($age >= 0 && $age <= 150) {
            $this->age = $age;
        }
    }
}

$user = new User();
$user->setEmail("john@example.com");
$user->setAge(25);

echo $user->getEmail(); // john@example.com
echo $user->getAge(); // 25

Setters can validate data before storing it. If validation fails, the setter can ignore the update, keeping the existing value intact. You can create read-only properties by providing only a getter, or write-only properties with only a setter.

Try it yourself

<?php
require_once 'Product.php';

// Read inputs
$name = trim(fgets(STDIN));
$price = trim(fgets(STDIN));
$stock = trim(fgets(STDIN));
$newPrice = trim(fgets(STDIN));

// TODO: Create a new Product instance

// TODO: Use setters to assign initial name, price (as float), and stock (as integer)

// TODO: Print the result of getInfo()

// TODO: Update the price with newPrice (as float) and print getInfo() again

// TODO: Attempt to set stock to -5 (invalid) and print getInfo() to confirm stock wasn't changed

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming