PHP Snippets: Property Hooks

Published: (January 9, 2026 at 12:37 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Property Hooks in PHP 8.5

PHP 8.5 introduces property hooks, allowing you to attach getter and setter logic directly to a property.

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

$berry = new Berry();
$berry->name = "  strawberry  ";
echo $berry->name; // Strawberry

The get hook capitalizes the first letter when the property is read, while the set hook trims whitespace when the property is written. No separate methods are required, keeping the logic close to the property definition.

How It Was Done Before PHP 8.5

Prior to property hooks, you needed a private property together with explicit getter and setter methods:

class Berry
{
    private string $name;

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

    public function setName(string $value): void
    {
        $this->name = trim($value);
    }
}

$berry = new Berry();
$berry->setName("  blueberry  ");
echo $berry->getName(); // Blueberry

The result is the same, but the code is more verbose and the transformation logic is separated from the property declaration.

Benefits of Property Hooks

  • Reduced boilerplate – no need for separate getter/setter methods.
  • Improved readability – the transformation logic lives right where the property is defined.
  • Easier maintenance – changes to the logic are made in a single place.
  • Cleaner class design – fewer private properties and public methods cluttering the class.

Welcome to modern PHP!

Back to Blog

Related posts

Read more »

PHP Attribute: SensitiveParameter

If you're not using it, the risk is already live. The SensitiveParameterhttps://www.php.net/manual/en/class.sensitiveparameter.php attribute introduced in PHP 8...