James John – Software Engineer

How I redefined my Getters & Setters Methods with Enums

PHP Enums came in with 8.1 and it has been a very groundbreaking feature introduced into PHP. For me, the getters and setters approach has been modified. Some people agree that the Getters and Setters system is outdated since the defined data type for objects came out, but I still find myself trying to run some line of instructions before assigning data to an object, I still use the setters. But instead of having setPhone() and getPhone() methods in the code, I prefer just phone() acting as both getter and setter. How do I achieve this? Enums!

Currently, this is what the getter and setter code looks like this:

The Close Call

I could try to use the new idea to merge both the getter and setter into one method without using Enum:

This is really close to the idea. But the flaw here is that; what happens when you have a nullable property? The setter will always run as a getter because it is passing its default value. This is where Enums come in, the unique data type!

The Call

To explain this, we depend on the uniqueness of the Enumerations data type, unlike null or any other data type you might choose, you might just run into a conflict in the future when a new property accepts that data type. So, passing a default value of an enum with its uniqueness can be used to control the behavior of a method, based on a condition.

To put this in action, we have to create the enum.

Then the modified methods:

The Result

Now we have one method for both getting and setting, which can be expressed like this:

Let me know your thoughts!

James John

Software Engineer