Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Mark Ragazzo:
Immutable objects
May 04, 2016 @ 18:55:42

In a post to his site Mark Ragazzo looks at immutable objects - what they are and how they can be used in a PHP application with some "final" functionality.

In this short article we will see what immutable objects are and why we should consider to use them. Immutable object is an object that does not change its state after it was created. Immutable objects usually are very simple. You may already seen them as enum types or primitives like DateTimeImmutable.

Further in this article you will learn that making simple objects immutable may save significant amount of your time by making impossible to make certain types of mistakes.

He starts with a list of a few things to remember when implementing immutable objects (like using the "final" keyword) and problems that can come without them. He then gets into some examples, showing how to create immutable Address and Money objects and how to use them when you need to update/get values from the object. He also covers some common "accidental mutability" cases like leaking internal object references and inheritance problems.

tagged: immutable object introduction example mutability accidental tutorial

Link: https://ragazzo.github.io/immutability/oop/2016/05/03/immutability.html

Derick Rethans:
DateTimeImmutable
Feb 26, 2014 @ 16:26:45

In his latest post Derick Rethans (knower of all things date and time) talks about the DateTimeImmutable functionality. It has been added into the PHP 5.5 releases and provides the same DateTime functionality but removes the ability for modification (mutability).

The first time that my improved DateTime support made its way into PHP was officially in PHP 5.1, although the more advanced features such as the DateTime class only made it appearance in PHP 5.2. Since its introduction the DateTime class implementation suffered from one design mistake - arguably not something that even an RFC would have highlighted. [...] This mutability property that all modifying methods of the DateTime class have is highly annoying, and something that I would now rather remove. But of course we cannot as that would break backwards compatibility. So in PHP 5.5, after a few stumbles, I finally managed to rectify this.

He includes some code examples showing the current DateTime object's mutability (via the "modify" function) and the new immutable handling. This new handling doesn't update the current object but instead returns the modified object, leaving the initial one intact. You can find out more about this new object in the PHP manual.

tagged: datetime datetimeimmutable mutability return object php55

Link: http://derickrethans.nl/immutable-datetime.html


Trending Topics: