PHP 8.4 Property Hooks: The Ultimate Guide for Developers

PHP
Harish Kumar · · 5136 Views

PHP 8.4, coming in November 2024, introduces a new feature called property hooks. This feature makes it easier to work with class properties by allowing you to define custom behavior when getting or setting property values.

In this article, we'll explain what property hooks are, how they work, and provide simple examples to help you understand how to use them.

What Are PHP Property Hooks?

Property hooks let you add custom logic directly to class properties. This means you can interact with properties like $person->name without needing separate methods like $person->getName() or $person->setName().

If you’ve used Laravel before, you might recognize that property hooks are similar to Laravel’s accessors and mutators, which also allow you to control how data is accessed and modified.

The "get" Hook

The get hook is used to control what happens when you access a property. For example, let's say you have a Person class, and you want to ensure that whenever you access the fullName property, it returns the first name and last name combined:

class Person
{
    public string $fullName {
        get {
            return $this->firstName . ' ' . $this->lastName;
        }
    }

    public function __construct(
        public string $firstName,
        public string $lastName
    ) {}
}

$person = new Person('John', 'Doe');

echo $person->fullName; // John Doe

In this example, when you access $person->fullName, the get hook combines firstName and lastName and returns "John Doe".

Type Compatibility

The type of the value returned by the get hook must match the type declared for the property. If the types don’t match, PHP will try to convert the value automatically unless strict types are enabled. If strict types are enabled, you need to ensure that the returned value exactly matches the property’s type, or an error will occur.

The "set" Hook

The set hook is used to control what happens when you assign a value to a property. For example, let’s say you want to ensure that any name assigned to a Person class is stored in uppercase:

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

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

$person = new Person('john');

echo $person->name; // JOHN

In this example, when you set $person->name to "john", the set hook automatically converts it to "JOHN" before storing it.

Type Compatibility

Similar to the get hook, the type of the value passed to the set hook must be compatible with the property’s type. If the types don’t match, PHP will raise an error if strict types are enabled.

Using "get" and "set" Hooks Together

You can use both get and set hooks on the same property to control how it is accessed and modified. For example, let’s create a Person class where the fullName property automatically splits a full name into first and last names when it’s set, and combines them when it’s accessed:

class Person
{
    public string $fullName {
        get {
            return $this->firstName . ' ' . $this->lastName;
        }
        set(string $value) {
            [$this->firstName, $this->lastName] = explode(' ', $value);
        }
    }

    private string $firstName;
    private string $lastName;

    public function __construct(string $fullName)
    {
        $this->fullName = $fullName;
    }
}

$person = new Person('John Doe');

echo $person->fullName; // John Doe

$person->fullName = 'Jane Smith';
echo $person->fullName; // Jane Smith

In this example, when you set $person->fullName to "Jane Smith", the set hook splits the name into firstName and lastName. When you access $person->fullName, the get hook combines these parts and returns "Jane Smith".

Write-only and Read-only Properties

With property hooks, you can create write-only or read-only properties.

  1. Write-only: You can only assign a value but not read it. This happens when you define a set hook but no get hook.

  2. Read-only: You can only read the value but not assign it. This happens when you define a get hook but no set hook.

Write-only Example

Here’s an example where you can only set a password but not read it:

class User
{
    public string $password {
        set(string $value) {
            $this->hashedPassword = password_hash($value, PASSWORD_DEFAULT);
        }
    }

    private string $hashedPassword;
}

$user = new User();
$user->password = 'secret';
// echo $user->password; // Error: Cannot access write-only property

Read-only Example

Here’s an example where you can only read a calculated value but not set it directly:

class Circle
{
    public float $radius;

    public float $area {
        get {
            return pi() * $this->radius ** 2;
        }
    }

    public function __construct(float $radius)
    {
        $this->radius = $radius;
    }
}

$circle = new Circle(5);
echo $circle->area; // 78.5398...
// $circle->area = 100; // Error: Cannot set read-only property

Things to Keep in Mind When Using Property Hooks

When working with property hooks in PHP, there are several important points to consider:

  1. Object Properties Only: Property hooks can only be applied to object properties, not static properties. This means that if a property is static, it cannot have a hook.

  2. Override Behavior: Property hooks will override any default behavior for reading or writing to a property. This means the custom logic in the hooks will control how the property is accessed or modified.

  3. Access to Methods and Properties: Property hooks can access all the object’s methods and properties, whether they are public, private, or protected. This includes properties that might have their own hooks.

  4. No References Allowed: You cannot set references on hooked properties. This is because modifying a value by reference would bypass any set hook that is defined for the property.

  5. Inheritance and Hook Redefinition: In a child class, you can redefine individual hooks for a property by redefining the property and only the hooks you want to change. The type and visibility of the property follow their own rules, and each hook can independently override the parent class’s implementation.

Conclusion

Property hooks in PHP 8.4 make working with class properties easier and more flexible. By allowing you to control how properties are accessed and modified directly within the property definition, you can write cleaner and more intuitive code. Whether you're creating simple classes or more complex logic, property hooks are a powerful tool in your PHP toolkit.

Read more about property hooks in the RFC here.

.

🔥 Supercharge Your Development with Ctrl+Alt+Cheat

I’m super excited to introduce Ctrl+Alt+Cheat, the ultimate cheat sheet extension for VSCode.

👉 Download Ctrl+Alt+Cheat today and start coding like a pro!

0

Please login or create new account to add your comment.

0 comments
You may also like:

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

PHP Security Guide: Strategies for Safe and Secure Code

PHP is one of the most widely used server-side scripting languages for web development, powering millions of websites and applications. Its popularity is largely due to its ease (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Transfer Objects (DTOs) in PHP: Streamlining Data Flow and Enhancing Code Clarity

Data Transfer Objects (DTOs) are simple objects used to transfer data between software application subsystems. They help in encapsulating data and reducing the number of method (...)
Harish Kumar

PHP Generators: Efficient Data Handling and Iteration Techniques

PHP Generators offer a powerful and memory-efficient way to handle large datasets and complex iteration scenarios in your applications. They provide a more elegant solution compared (...)
Harish Kumar

Compress and Download Files in Laravel Using ZipArchive with Examples

In web development, file compression is essential for optimizing data transfer and storage. Laravel provides tools for creating and downloading compressed files. This guide explores (...)
Harish Kumar