rfc:immutability

This is an old revision of the document!


PHP RFC: Immutable classes and properties

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

  1. Immutability guaranteed by language instead of user-land implementation.
  2. Safe for concurrency.
  3. Value objects, DTO's etc. can be easily created.
  4. Properties can be public which removes need for getters without allowing state modification.
  5. (Please point it out more advantages)

Cons

  1. Cloning has to be disabled for immutable objects
  2. (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

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature

References

Rejected Features

rfc/immutability.1471015101.txt.gz · Last modified: 2017/09/22 13:28 (external edit)