eboreum / immutable-interface
Flag a class as being immutable by implementing the ImmutableInterface. An immutable object must never change its state; i.e. its class properties must remain unchanged after instantiation or cloning.
Requires
- php: ^8.5
Requires (Dev)
- overtrue/phplint: ^9.7
- phpstan/phpstan: ^2.1
- slevomat/coding-standard: ^8.27
- squizlabs/php_codesniffer: ^4.0
README

Implement Eboreum\ImmutableInterface\ImmutableInterface on any class to flag it as being immutable. An immutable object must never change its state; i.e. its class properties must remain unchanged after instantiation or cloning.
Normal inheritance applies. Meaning once a class or interface has implemented/extended Eboreum\ImmutableInterface\ImmutableInterface, every child class/interface must also be considered to be immutable.
While you are not allowed to change the state of an object (e.g. through set... methods), you may instead do so on a clone and then return said clone. This is typically done using with... methods, which should have the return type static.
An alternative
If you do not like the inheritance pattern or if you have specific cases where you do not want inheritance to apply, you may instead use these libraries in combination:
- php-static-analysis/attributes: Defines the
@immutableannotation. - php-static-analysis/phpstan-extension: A
--devpackage, which reacts to the annotations defined in php-static-analysis/attributes (bullet 1).
Requirements
"php": "^8.5"
Installation
Via Composer (https://packagist.org/packages/eboreum/immutable-interface):
composer require eboreum/immutable-interface
Via GitLab:
git clone git@gitlab.com:eboreum/immutable-interface.git
License & Disclaimer
See LICENSE file. Basically: Use this library at your own risk.
Contributing
We prefer that you create an issue and or a merge request at https://gitlab.com/eboreum/immutable-interface, and have a discussion about a feature or bug here.
Credits
Authors
- Kasper Søfren (kafoso)
E-mail: soefritz@gmail.com
Homepage: https://gitlab.com/kafoso / https://github.com/kafoso