Skip to content

PHP 8.4 Property Hooks Tutorial: Replace Repetitive Getters and Setters

What Are Property Hooks in PHP 8.4?

Before PHP 8.4, developers usually created separate getter and setter methods when a property required validation or transformation.

<?php

class User
{
    private string $name;

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

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

PHP 8.4 allows this logic to be defined directly inside the property.

<?php

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

        get {
            return $this->name;
        }
    }
}

Whenever a value is assigned to name, leading and trailing spaces are automatically removed.

<?php

$user = new User();

$user->name = '  Ali Shahroodi  ';

echo $user->name;

Output:

Ali Shahroodi

Validating Values with a set Hook

A common use case for Property Hooks is validating a value before storing it.

<?php

class Product
{
    public float $price {
        set {
            if ($value < 0) {
                throw new InvalidArgumentException(
                    'The price cannot be negative.'
                );
            }

            $this->price = $value;
        }
    }
}

A negative value can no longer be assigned to the property:

<?php

$product = new Product();

$product->price = -100;

This code throws an InvalidArgumentException.

Creating a Computed Property

A get hook can also create a property whose value is calculated dynamically.

<?php

class Person
{
    public string $firstName = '';
    public string $lastName = '';

    public string $fullName {
        get {
            return "{$this->firstName} {$this->lastName}";
        }
    }
}

Usage:

<?php

$person = new Person();

$person->firstName = 'Ali';
$person->lastName = 'Shahroodi';

echo $person->fullName;

Output:

Ali Shahroodi

The fullName property is calculated whenever it is accessed and does not need its own stored value.

Short Hook Syntax

Simple hooks can also use a shorter arrow-function syntax:

<?php

class Article
{
    public string $title {
        set => trim($value);
    }
}

This automatically trims the article title before storing it.

Conclusion

Property Hooks in PHP 8.4 allow developers to attach custom behavior directly to property read and write operations.

They can be used to:

  • Validate assigned values
  • Transform data before storing it
  • Create computed properties
  • Reduce repetitive getter and setter methods
  • Keep classes shorter and easier to read

PHP 8.4 or a newer version is required to run the examples in this tutorial.

Leave a Comment

Your email address will not be published.