Hi internals,
In OOP it's a sometimes a common issue to know the state of an object
and to know if it was changed respectively it it can change state.
We already have such objects like DateTImeImmutable and new proposed
objects like UString also introduce immutable objects.
I think it would be really helpful to see this kind of issue addressed
in a standardized way:
if you approve with this I would write down a more structured RFC.
Now see the following code snipped:
<?php
immutable class MyImmutableClass {
public static $staticProperty = 'private static';
public $ts;
public $obj;
public function __construct($obj = null) {
$this->ts = time();
$this->setObj($obj);
}
public function getTimestamp() { return $this->ts; }
public function getObj() { return $this->obj; }
public function setObj($obj) { $this->obj = $obj; }
}
// initialize
$obj = new DateTImeImmutable();
$obj = new MyImmutableClass($obj);
// check if immutable
var_dump(MyImmutableClass::immutable);
var_dump($obj::immutable);
// read properties
var_dump($obj->ts, $obj->obj);
var_dump($obj->getTimestamp(), $obj->getObj());
// ERROR: Immutable objects can not contain mutable properties
$obj = new MyImmutableClass(new stdClass);
// ERROR: Immutable objects can not be changed after initialization
$obj = new MyImmutableClass();
$obj->setObj($obj);
$obj->obj = $obj;
// ERROR: It's not allowed to change immutable variables
MyImmutableClass::$staticProperty = 'new value';
?>
Because of for immutable objects it's not allowed to set an mutable
object as property
you can be sure the object's state will be consistent. That's the main
difference from
marking all properties readonly or similar functionalities.
Additionally it's simple to test if an class/object is immutable and
document it for free.
Downside: New Keyword "immutable"
/<http://dict.leo.org/#/search=adv.&searchLoc=0&resultOrder=basic&multiwordShowSingle=on>/