From Old Habits to Modern Best Practices: Introducing Enums

jochelle mendonca
4 min readApr 23, 2024

Have you ever stared at a giant switch statement in your PHP code, muttering, “There has to be a better way!”?

Photo by Roman Synkevych on Unsplash

Well, fret no more, because enums are here to banish those cryptic magic numbers and bring clarity to your data!

Whether you’re just starting out or a seasoned pro, enums are a powerful tool that can streamline your code and make your development process smoother.

Imagine a world where instead of using constants like COLOR_RED set to the value 1, you could define an enum Color with cases like RED, GREEN, and BLUE. Sounds pretty neat, right? That's the magic of enums!

A Bird’s-Eye View

Think of enums as a fancy way to create a set of predefined constants that belong to a specific category. It’s like creating a special club with a limited membership — only values that fit the category can join! This ensures type safety and makes your code more readable and maintainable.

Back in the early days of my PHP journey, enums were a foreign concept to me. Like many developers, I relied on magic numbers and strings to represent fixed sets of values. While this approach got the job done, it often led to confusion, bugs, and spaghetti code.

As I delved deeper into the PHP ecosystem, I discovered the power of enums. They provided a structured way to define and manage constants, leading to more readable, maintainable code. From that moment on, enums became a staple in my development arsenal.

Benefits Galore: Why You Should Use Enums

  • Clarity over Confusion: No more wondering what that mysterious 3 in your code means. Enums make your intentions crystal clear!
  • Type Safety: Enums act like bouncers for your data, ensuring only valid values enter the club. This reduces errors and makes debugging a breeze.
  • Improved Readability: Code with enums becomes more self-documenting. Just by looking at the enum definition, you understand the possible values.
  • Modern and Trendy: Enums are the new cool kids on the PHP block. Embrace them and show off your code’s sophistication!

Let’s Get Coding: Creating Your First Enum

Alright, enough talk, let’s see enums in action! Here’s how to create a basic Status enum:

enum Status: string {
case Pending = "pending";
case Approved = "approved";
case Rejected = "rejected";
}

$orderStatus = Status::Pending; // Assigning the "Pending" case
echo $orderStatus; // Outputs "pending"

See how easy that was? We defined an enum named Status with three cases: Pending, Approved, and Rejected.

Each case has a corresponding string value. Now, you can safely assign these cases to variables and use them throughout your code.

Beyond the Basics: Advanced Enum Features

Enums offer more than just simple string values. You can also:

  • Use Integers: Define enums with integer values for a more compact representation.
  • Set Default Values: Assign a default value to each case.
  • Implement Interfaces: Make your enums even more powerful by implementing interfaces.

Pro Tips and Tricks for the Discerning Developer

  • Leverage Enum Methods: Enums come with built-in methods like name and value to access the case name and value, respectively.
  • Use Enum Cases in Comparisons: You can directly compare enum cases using the equality operator (===).
  • Think Outside the Box: Enums are versatile! Use them for things like permission levels, user roles, or even weekdays.

A few more scenarios:

Basic Enum:

enum LogLevel {
case DEBUG;
case INFO;
case WARNING;
case ERROR;
}

$logLevel = LogLevel::DEBUG;

Enum with Associated Values:

enum UserRole {
case ADMIN(string $username);
case MODERATOR(string $username);
case MEMBER;
}

$userRole = UserRole::ADMIN("john_doe");

Enum with Methods:

enum TrafficLight {
case RED;
case YELLOW;
case GREEN;

public function isSafeToProceed(): bool {
return $this === self::GREEN;
}
}
$trafficLight = TrafficLight::GREEN;
if ($trafficLight->isSafeToProceed()) {
echo "It's safe to proceed.";
}

Enums: A Game Changer for Your Code

Enums have come a long way since their humble beginnings, evolving into a powerful tool for PHP developers. By embracing enums, you’ll write cleaner, more maintainable, and less error-prone code.

So, ditch those magic numbers and join the enum revolution! Remember, with great enums comes great responsibility (okay, maybe not that dramatic).

But seriously, use them wisely and watch your code transform!

Happy coding!

If you liked this article and would like to support me, make sure to:

  • 👏Clap for this story
  • 🔔Follow me on Medium
  • ☕️ If you feel my work is worth an appreciation, you can buy me a coffee!

--

--

jochelle mendonca

Passionate PHP developer. Enthusiastic about the power of words, equally adept at reading and writing