← cd ../blog

PHP 8.4 property hooks: goodbye boilerplate getters

For years, a "simple" value object in PHP meant a constructor, private properties and a pile of getters and setters. PHP 8.4 changes that with property hooks.

Before

class User
{
    private string $email;

    public function setEmail(string $email): void
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('Invalid email');
        }
        $this->email = strtolower($email);
    }

    public function getEmail(): string
    {
        return $this->email;
    }
}

After

class User
{
    public string $email {
        set {
            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                throw new InvalidArgumentException('Invalid email');
            }
            $this->email = strtolower($value);
        }
    }
}

The property is public, the validation is enforced, and the call site is just $user->email = 'A@B.it'.

Virtual properties

Hooks can also compute values without any storage:

class Rectangle
{
    public function __construct(public float $w, public float $h) {}

    public float $area {
        get => $this->w * $this->h;
    }
}

Asymmetric visibility

Need public read but private write? One keyword:

public private(set) string $id;

Less ceremony, same guarantees. That's the kind of language evolution I like.