Use Property Hooks in PHP 8.4

Use Property Hooks in PHP 8.4

Since PHP 8.4, we can use property hooks, which enables defining custom getter and setter logic directly for class properties, eliminating the need for separate getter and setter methods. The purpose of property hooks is to eliminate the need for writing repetitive code.

In the provided code, the Person class defines a private $phone property along with custom getter and setter methods. The setPhone method takes a string as input and sanitizes it by removing all non-digit characters. The getPhone method prepends a + symbol and returns a formatted phone number.

Person.php

<?php

class Person
{
    private string $phone;

    public function getPhone(): string
    {
        return '+'.$this->phone;
    }

    public function setPhone(string $phone): void
    {
        $this->phone = preg_replace('/\D+/', '', $phone);
    }
}
<?php

require_once __DIR__.'/Person.php';

$person = new Person();
$person->setPhone('1 (611) 112-2333');
echo $person->getPhone(); // +16111122333

Since PHP 8.4, we can rewrite code using property hooks. By integrating the logic directly into the property definition, the need for separate methods is eliminated, reducing redundant code and improving readability. This approach keeps the code concise while maintaining encapsulation. Additionally, developers interact with properties in a natural and intuitive way, using assignment and retrieval syntax.

Person.php

<?php

class Person
{
    public string $phone {
        get => '+'.$this->phone;
        set (string $phone) => $this->phone = preg_replace('/\D+/', '', $phone);
    }
}
<?php

require_once __DIR__.'/Person.php';

$person = new Person();
$person->phone = '1 (611) 112-2333';
echo $person->phone; // +16111122333

There are some important notes:

  • The syntax allows defining either the set hook or the get hook independently; both hooks do not need to be defined together.
  • If a property has at least one hook and neither hook references $this->propertyName, no data is automatically stored in the object. These properties are known as virtual properties.

In the following code, the $adult is virtual property because does not use $this->adult. Attempt to write to this property will result in an Error being thrown.

Person.php

<?php

class Person
{
    public string $name {
        get => ucwords($this->name);
    }

    public int $age {
        set (int $age) {
            if ($age < 0) {
                throw new InvalidArgumentException();
            }
            $this->age = $age;
        }
    }

    public bool $adult {
        get => $this->age >= 18;
    }
}
<?php

require_once __DIR__.'/Person.php';

$person = new Person();
$person->name = 'john';
echo $person->name; // John
$person->age = 20;
echo $person->age; // 20
var_dump($person->adult); // true

Leave a Comment

Cancel reply

Your email address will not be published.