Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 Elephpant {
        public string $trunkLength {
            // this is the single line definition of a hook
            // the expression is the returned value
            get => $this->trunkLength . '1';

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

?>

Documentation

See Also