PHP 8.4 introduces property hooks

The new PHP version introduces, among other things, property hooks, asymmetric visibility for class properties, and a new HTML5 DOM API.

With property hooks, get and set logic can be defined directly on the property declaration (similar to C#), rather than using separate getFoo()/setFoo() methods or the somewhat unwieldy magic methods __get/__set as before. This significantly improves the flexibility and readability of the code.

Before property hooks, the get and set logic looked like this:

				
					<?php

class Intxample
{ 
    private bool $negative = false;
    public int $value = 0;
    
    public function getValue(): int
    { 
        if ($this->negative) { 
            return $this->value * -1; 
        } 
        
        return $this->value; 
        
    }
    
    public function setValue(int $value)
    {
        $this->value = abs($value);
        $this->negative = $value < 0;
    }
}

$example = new Intxample();
$example->setValue(-5);
print $example->getValue(); // Output: -5
				
			

In comparison, here is the new syntax:

				
					<?php

class Intxample
{
    private bool $negative = false;

    public int $value = 0 {
    
        get {
            if ($this->negative) {
                return $this->value * -1;
            }
            return $this->value;
        }
        
        set(int $value) {
            $this->value = abs($value);
            $this->negative = $value < 0;
        }
    }
}

$example = new Intxample();
$example->value = -5;
print $example->value; // Output: -5
				
			

Whether this really brings such a big advantage for developers is up for debate. From my point of view, it makes the variable block at the beginning of a class much more confusing. I suppose that’s a matter of taste.

About the Author

WordPress Cookie Notice by Real Cookie Banner