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

Simon Holywell:
PHP and immutability
Mar 22, 2017 @ 16:21:37

In a recent post to his site Simon Holywell covers immutability in PHP. PHP, by default, uses weak typing and doesn't support much in the way of immutability but Simon shows you a few ways you can get around this and make immutable objects you can use and extend.

Being a weakly typed dynamic language, PHP has not really had the concept of immutability built into it. We’ve seen the venerable define() and CONSTANTS of course, but they’re limited. Whilst PHP does ship with an immutable class as part of it’s standard library, DateTimeImmutable, there is no immediately obvious method to create custom immutable objects.

[...] It is possible to write your own immutables using some simple and sneaky PHP techniques though. We’re going to use a simplistic data requirement to make the examples in this article easier to follow. I’ll be using professional skateboarders and the tricks that they brought to the world.

He starts the article talking about immutability and how it relates back to the current (as of PHP 7) values supported in constants - scalars and arrays (no objects). He then starts on the code to create the base Immutable class that sets its values via the constructor. He then points out some of the common "work arounds" people use when trying to work with immutable objects and some techniques to help prevent it: the use of final, a "flag" preventing another constructor call, etc.

tagged: immutable tutorial technique php7 constant

Link: https://www.simonholywell.com/post/2017/03/php-and-immutability/


Trending Topics: