This trait makes it super easy to turn an instance immutable or mutable.
php-immutable-trait is installable via Composer
composer require jclaveau/php-immutable-trait
class ImmutableObject
{
use Immutable;
// use SwitchableMutability; // This traits provides becomesMutable() and becomesImmutable()protected$property;
publicfunctionsetProperty($value)
{
// Just add these lines at the really beginning of methods supporting// immutability (setters mostly)if ($this->callOnCloneIfImmutable($result))
return$result;
// $this is now the new instance if it's immutable$this->property = $value;
return$this;
}
publicfunctiongetProperty()
{
return$this->property;
}
}
$instance = newImmutableObject;
$instance2 = $instance->setProperty('new value');
var_dump( $instance->getProperty() ); => nullvar_dump( $instance2->getProperty() ); => 'new value'- Profiles
- PHP 7
- Support immutability for private / protected methods? Should the dev handle it? Should we provide a simple protected API for it?
