You may have seen the
\DateTimeImmutable class being used, and wondered why is this different from the
\DateTime class? I guess it’s the same…but immutable, right? Why would I want to use an immutable object? Here’s a brief overview.
Why use an immutable class?
In php, when you pass around an object by assigning it to a variable, you are actually creating another reference to that object, rather than creating another version of it.
You can see from the example above, that when we created
$person2 we just referenced
$person1. This means they don’t just share the same state, but they are actually the same object; the same data in memory. Now, you’re unlikely to write code like the example above, but it might start to become apparent of the possible problems when using fluent setters. Here’s another example:
This will create a new start time, of now, and then create a new end time which is 1 day after the start time. But wait…we created the new end time by assigning it the value returned from
$startTime->add(). This both added an interval to the start time and returned itself. This means that if we output the value of
$startTime, it will be 1 day from now.
At this point,
$endTime are effectively the same. The way we get around this is to use a class which creates an immutable object. As it happens, there is a
/DateTimeImmutable class just right for the job.
How do you create an immutable class?
An immutable class is no different than any other class, apart from the state can never be changed. Each time you want to change the value of a particular property, a new object is returned with the new value. For example:
Also note that the setter methods are prefixed with
with rather than
set. This is a common convention when creating immutable objects. These immutable objects are also known as a value objects, as any two objects are never the same (one does not equal the other), even though the values or state that they represent could be.
I hope you found this helpful. Let me know in the comments any thoughts or questions about value objects or immutability.