On the Laravel News site there’s a tutorial posted showing how to work effectively with mutable and immutable DateTime functionality in PHP. The DateTime functionality has long been bundled with the language and offers powerful tools for working with dates, improving on what the basic date function provides.
Mutable dates can be the source of confusion and unexpected bugs in your code. My goal isn’t to tell you that DateTime is evil because it’s mutable, but to consider the tradeoffs and benefits of using mutable versus immutable DateTime objects. Either approach warrants a good test suite and an awareness of how modifier methods affect your date objects.
Until recently, I wasn’t even aware that PHP offers a counterpart to the DateTime class: DateTimeImmutable. The DateTimeIummtable class works just like the DateTime class, except that it never modifies itself, but returns a new object instead. So if you know how to work with DateTime, you immediately can work with DateTimeImmutable.
The article starts by talking about mutable DateTime objects and shows examples of using the Carbon date handling package as a layer on top of PHP’s DateTime handling. It includes code examples of mutable objects. It then moves on to the immutable objects, covering the differences between the two complete with code examples. The post ends with a bit more information about mutable vs immutable and links to the Chronos documentation for more information on another date handling library.