PHP 8: Modern PHP Development · Object-Oriented PHP 8

Property Hooks and Asymmetric Visibility (PHP 8.4)

Replace boilerplate getters/setters with property hooks and public-read, private-write properties.

PHP 8.4 added property hooks: get and set logic attached directly to a property, so you keep simple $obj->prop access while validating or computing values. Asymmetric visibility lets a property be publicly readable but only privately (or protected) writable: public private(set) string $name. Together they remove much getter/setter boilerplate. Virtual properties (hooks without backing storage) compute values on access.

<?php
final class User
{
    public function __construct(
        public private(set) string $email,
        public string $firstName,
        public string $lastName,
    ) {}

    // Virtual property: computed, no storage
    public string $fullName {
        get => "{$this->firstName} {$this->lastName}";
    }

    // Validation on write
    public string $username {
        set(string $value) {
            if (!preg_match('/^[a-z0-9_]{3,20}$/', $value)) {
                throw new InvalidArgumentException('Invalid username');
            }
            $this->username = strtolower($value);
        }
    }

    public function changeEmail(string $email): void { $this->email = $email; }
}

$u = new User('[email protected]', 'Ada', 'Lovelace');
echo $u->fullName;          // Ada Lovelace
// $u->email = 'x';         // Error: cannot modify private(set) property

Common pitfalls

  • Hooks run on every access — avoid expensive work in get hooks.
  • Property hooks require PHP 8.4; libraries supporting older versions can't use them.
  • Hooks can't be combined with readonly properties.

Key points

  • Hooks keep property syntax with getter/setter logic
  • public private(set) gives read-only access from outside
  • Virtual properties compute values

Further reading: PHP manual: property hooks

Practice questions

What does public private(set) string $email mean?

Answer

The property can be read from anywhere but only assigned from inside the class (asymmetric visibility, PHP 8.4). It's a lightweight alternative to a private property plus a public getter.

Why might you use a property hook instead of a setter method?

Answer

To keep natural property access ($user->username = 'x') while enforcing validation or normalization, and to evolve a public property into computed logic without changing callers.

Open in the app to mark lessons complete, take notes and track your progress.