Skip to content

Repository files navigation

Immutable Trait

This trait makes it super easy to turn an instance immutable or mutable.

Quality

Build Statuscodecovcontributions welcomeViewed

Installation

php-immutable-trait is installable via Composer

composer require jclaveau/php-immutable-trait

Usage

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'

TODO

  • Profiles
  • PHP 7
  • Support immutability for private / protected methods? Should the dev handle it? Should we provide a simple protected API for it?

About

A trait providing togglable immutability to whatever you want

Resources

Stars

3 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages