This is an old revision of the document!
PHP RFC: Immutable classes and properties
- Version: 0.1
- Date: 2016-08-12
- Authors: Michal Brzuchalski michal@brzuchalski.com, Silvio Marijic marijic.silvio@gmail.com
- Status: In Draft
- First Published at: 2016-08-12
Introduction
This RFC proposes introduction of immutable classes and properties. Currently PHP lacks native support for immutability. Because of that user-land applications are using third party libraries or resort to custom implementations and still there is no easy enforcement of immutability. Introducing this feature would help bring one unified solution to this problem, and also it would remove unnecessary logic from user-land applications.
Pros
- Immutability guaranteed by language instead of user-land implementation.
- Safe for concurrency.
- Value objects, DTO's etc. can be easily created.
- Properties can be public which removes need for getters without allowing state modification.
- (Please point it out more advantages)
Cons
- (Please point it out more disadvantages)
Before
<?php class Email { private $_email; public function __construct ($email) { // validation $this->_email = $email; } public function getValue() { return $this->_email; } }
After
<?php immutable class Email { public $email; public function __construct ($email) { // validation $this->email = $email; } }
Proposal
Class defined as immutable will imply immutability across all of it's properties by default. Regular classes can define immutability per property. After constructor returns, it will not be possible to modify state of immutable properties from any scope. Any class that extends immutable class must be also declared as immutable. It will not be possible to assign value by reference to immutable property. If immutable property contains object, object must also be an instance of immutable class.
immutable class Email { public $email; public function __construct ($email) { // validation $this->email = $email; } } $email = new Email("foo@php.net"); $email->email = "bar@php.net" // Call will result in Fatal Error
Backward Incompatible Changes
No backward incompatible changes.
Proposed PHP Version(s)
- PHP 7.2
RFC Impact
To SAPIs
No SAPI impact.
To Existing Extensions
- Reflection.
To Opcache
New Constants
No new constants.
php.ini Defaults
No changes for INI values.
Open Issues
No open issues.
Unaffected PHP Functionality
Future Scope
Proposed Voting Choices
Proposals require 2/3 majority
Patches and Tests
Implementation
After the project is implemented, this section should contain
- the version(s) it was merged to
- a link to the git commit(s)
- a link to the PHP manual entry for the feature