Search code examples
phpimmutability

PHP: immutable public member fields


I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final keyword before each field. How is it done in PHP?


Solution

  • You should use __set and __get magic methods and declare that property as protected or private:

    /**
     * @property-read string $value
     */
    class Example
    {
        private $value;
    
        public function __construct()
        {
            $this->value = "test";
        }
    
        public function __get($key)
        {
            if (property_exists($this, $key)) {
                return $this->{$key};
            } else {
                return null; // or throw an exception
            }
        }
    
        public function __set($key, $value)
        {
            return; // or throw an exception
        }
    }
    

    Example:

    $example = new Example();
    var_dump($example->value);
    $example->value = "invalid";
    var_dump($example->value);
    

    Outputs:

    string(4) "test"
    string(4) "test"
    

    @property-read should help your IDE acknowledge existence of this magic property.