Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 773
snakile Avatar asked Sep 06 '11 08:09

snakile


People also ask

Are PHP variables immutable?

Traditional constants, set with define() , can be initialised conditionally and be built from other variables - once set though, they are immutable.

Is PHP string immutable?

In Ruby and PHP, strings are mutable. The C language does not really have string objects per se. However, we commonly represent strings as a pointer char *. In general, C strings are mutable.

What is mutable and immutable in PHP?

Mutability In PHPIf the method changes the data referenced by the object's zval, it is considered to be mutable. If the method does not change the data referenced, it is considered immutable.

What does immutable mean in PHP?

Immutable Class A class defined as immutable will imply immutability across all of its properties by default. After the object is constructed, it is not possible to modify the state of the object from any scope.


1 Answers

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.

like image 184
sanmai Avatar answered Sep 30 '22 13:09

sanmai