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?
Traditional constants, set with define() , can be initialised conditionally and be built from other variables - once set though, they are 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With