Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable objects in PHP?

Is it a good idea to create objects that cannot be changed in PHP?

For example a date object which has setter methods, but they will always return a new instance of the object (with the modified date).

Would these objects be confusing to other people that use the class, because in PHP you usually expect the object to change?

Example

$obj = new Object(2);

$x = $obj->add(5); // 7
$y = $obj->add(2); // 4
like image 923
Elfy Avatar asked Jan 20 '13 17:01

Elfy


People also ask

What does immutable mean in PHP?

"Immutable": - Unchanging over time or unable to be changed. If you want an immutable object it means it cannot be changed after instantiation.

What is mutable and immutable in PHP?

It refers to whether or not a method on the object changes the data referenced by that object's pointer (or in the case of PHP, its zval). If the method changes the data referenced by the object's zval, it is considered to be mutable. If the method does not change the data referenced, it is considered immutable.

Which is an immutable object?

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

Are PHP variables immutable?

The only immutable data store available in PHP is constants, which are set with define() or the const keyword on a PHP class. There is one important difference between the two options though. Class constants ( const ) are set when the code is written and cannot be changed at runtime.


1 Answers

Immutable objects don't have setter methods. Period.

Everyone will expect a setXyz() method to have a void return type (or return nothing in loosely typed languages). If you do add setter methods to your immutable object it will confuse the hell out of people and lead to ugly bugs.

like image 58
ThiefMaster Avatar answered Oct 09 '22 06:10

ThiefMaster