Property Hook

Property hooks are a feature of PHP 8.4, where accessors can be defined with the property.

Hooks are for set and get: they allow extra commands to be always executed at setting or getting time of a property.

Hooks look like the magic methods __set and __get, with a few differences: they are dedicated to a property, and easier to write.

Property hooks are also called Property Accessors, in other languages.

<?php

    class X {
        public string $property {
            // this is the single line definition of a hook
            // the expression is the returned value
            get => $this->property . '1';

            set {
                // $value is the unique parameter of that function
                $this->property = $value;
            }
        }
    }

?>

Documentation

See also PHP 8.4 Property Hooks, PHP 8.4 Property Hooks: The Ultimate Guide for Developers, PHP RFC: Property hook improvements, A Guide to PHP 8.4 Property Hooks, PHP’s New Property Hooks Are Here—But Should You Use Them? and Using property hooks in PHP.

Related : Properties, __get() Method, __set() Method, Magic Methods, Double Arrow, Magic Constants, Virtual Property, Writeable, Class Getter Method, Property Type Declaration

Added in PHP 8.4