Enum w PHP to skrót od “enumeration”, co oznacza zestawienie lub wyliczenie. Jest to typ danych, który umożliwia programiście definiowanie zestawu stałych wartości, które mogą być używane w kodzie.
Pojawienie się enumów w PHP jest związane z wprowadzeniem nowych możliwości programowania obiektowego. Tradycyjnie PHP nie posiadał natywnego wsparcia dla enumów, ale od wersji PHP 8.1 wprowadzono możliwość definiowania enumów za pomocą nowego typu danych.
Jak działają enumy w PHP?
Enumy w PHP pozwalają programiście na zdefiniowanie zbioru stałych wartości, które są dostępne w obrębie danego typu. Wartości enumów są unikalne w ramach danego typu enum.
Przykład użycia enum w PHP
Zacznijmy od czegoś prostego. Zdefiniujmy kolory i go wyświetlmy przy użyciu Enum w PHP.
enum Color { case RED; case GREEN; case BLUE; } $color = Color::RED; echo $color; // Wyświetli: Color::RED
inny przykład, tym razem z dniami tygodnia:
enum DayOfWeek { case MONDAY; case TUESDAY; case WEDNESDAY; case THURSDAY; case FRIDAY; case SATURDAY; case SUNDAY; } function printDay(DayOfWeek $day) { switch ($day) { case DayOfWeek::MONDAY: case DayOfWeek::TUESDAY: case DayOfWeek::WEDNESDAY: case DayOfWeek::THURSDAY: case DayOfWeek::FRIDAY: echo "To jest dzień roboczy."; break; case DayOfWeek::SATURDAY: case DayOfWeek::SUNDAY: echo "To jest dzień wolny."; break; } } $today = DayOfWeek::MONDAY; printDay($today); // Wyświetli: To jest dzień roboczy.
W przykładzie powyżej, definiujemy enum o nazwie “DayOfWeek”, który reprezentuje dni tygodnia. Następnie tworzymy funkcję printDay()
, która przyjmuje argument typu DayOfWeek
i w zależności od dnia tygodnia wyświetla odpowiedni komunikat.
Dodatkowo zamiast używania switch możemy wykorzystać nowość, match z PHP 8.0 🙂 Zobacz jak to teraz będzie wyglądać:
enum DayOfWeek { case MONDAY; case TUESDAY; case WEDNESDAY; case THURSDAY; case FRIDAY; case SATURDAY; case SUNDAY; } function printDay(DayOfWeek $day) { echo match ($day) { DayOfWeek::MONDAY, DayOfWeek::TUESDAY, DayOfWeek::WEDNESDAY, DayOfWeek::THURSDAY, DayOfWeek::FRIDAY => "To jest dzień roboczy.", DayOfWeek::SATURDAY, DayOfWeek::SUNDAY => "To jest dzień wolny.", }; } $today = DayOfWeek::MONDAY; printDay($today); // Wyświetli: To jest dzień roboczy.
Funkcja match
jest alternatywą dla instrukcji switch
, która jest bardziej elastyczna i wyraźniejsza w wielu przypadkach. W powyższym przykładzie użyłem match
, aby dopasować wartość enuma DayOfWeek
i wyświetlić odpowiedni komunikat w zależności od dnia tygodnia.
BTW Warto zauważyć, że składnia match
jest bardziej zwięzła i czytelna w porównaniu do tradycyjnej instrukcji switch
, zwłaszcza gdy mamy do czynienia z wieloma możliwymi dopasowaniami!
Zastosowanie enumów:
Enumy są przydatne w wielu sytuacjach, zwłaszcza gdy mamy do czynienia z ograniczonym zestawem możliwych wartości, które mogą być przypisane do określonych właściwości lub używane w logice biznesowej. Przykładowe zastosowania enumów to:
- Reprezentacja statusów (np. aktywny, nieaktywny, zablokowany)
- Typy dni tygodnia (np. poniedziałek, wtorek, środa, …)
- Kategorie produktów (np. elektronika, odzież, artykuły spożywcze)
Enumy pozwalają uniknąć błędów związanych z literówkami czy nieprawidłowymi wartościami, a także ułatwiają czytelność kodu poprzez nadanie sensownych nazw stałym wartościom.
Jak wykorzystać enum w PHP?
- Definicja enuma: Zdefiniuj enum za pomocą słowa kluczowego “enum” oraz określ zestaw stałych wartości.
- Użycie enuma: Przypisuj wartości enuma do zmiennych lub wykorzystuj je w warunkach i pętlach.
- Ograniczenie możliwych wartości: Dzięki enumom możesz ograniczyć możliwe wartości danej zmiennej do zestawu zdefiniowanych stałych.
Enumy stanowią użyteczne narzędzie w programowaniu PHP, pomagając w tworzeniu czytelnego, bezbłędnego i łatwo skalowalnego kodu.
Wprowadzenie enumów do PHP to kolejny krok naprzód, który ułatwia programistom pracę nad bardziej czytelnym i zorganizowanym kodem.
Nikt jeszcze nie komentował. Bądź pierwszy!