Medium PHP

PHP 8.4 Property Hooks Explained

Discover the new property hooks feature in PHP 8.4 that provides a cleaner way to add logic to property access.

21 Jun, 2026 1 min 1,406 Views 3 Code blocks

PHP 8.4 Property Hooks

PHP 8.4 introduces property hooks, a powerful feature that allows you to add custom logic when getting or setting properties.

Basic Example

class User
{
    public string $name {
        get => strtoupper($this->name);
        set => ucfirst($value);
    }
}

$user = new User();
$user->name = 'john doe';
echo $user->name; // Output: JOHN DOE

Computed Properties

Create virtual properties without backing storage:

class Rectangle
{
    public function __construct(
        public float $width,
        public float $height
    ) {}

    public float $area {
        get => $this->width * $this->height;
    }
}

Validation in Setters

class Product
{
    private float $_price;

    public float $price {
        get => $this->_price;
        set {
            if ($value < 0) {
                throw new InvalidArgumentException('Price must be positive');
            }
            $this->_price = $value;
        }
    }
}

Benefits

  • ✅ Cleaner than __get() and __set() magic methods
  • ✅ Better IDE support and static analysis
  • ✅ More explicit and readable code
  • ✅ Type-safe property access

Property hooks make PHP objects more powerful while maintaining backward compatibility!

More from PHP