How to use Enum in PHP 8

Enums are one of the basic features of many programming languages, and PHP is no exception. Here's everything you need to know about Enums in PHP .

How to use Enum in PHP 8 Picture 1

Enumeration (enum) is a data type that you can use to store a value from a custom set. They're perfect for representing the type of options you can show in a drop-down list.

PHP 8.1 now supports enums. Using enums is easy but they provide additional features borrowed from object-oriented programming.

Effects of Enum

Enums are useful when you want to work with a fixed set of related values. For example, you can use an enum to represent sets in a card pack or media type.

PHP's enums are quite complex, with some features borrowed from classes. You can use them in combination with type hints to write more predictable and rigorous code.

Basic enums

Enums typically store scalar values. They are similar to C's primitive data types, although PHP enums can contain string values ​​as well as integers. However, by default, PHP enum values ​​do not have scalar equivalents. These are called basic enums:

enum Season {     case Spring;     case Summer;     case Autumn;     case Winter; }

Note how PHP reuses the case keyword, which you'll encounter in the switch statement. What the enum values ​​represent are just the names of the instances. You can refer to a specific enum value with the following command:

EnumTypeName::EnumField

For example, to refer to winter, use:

Season::Winter

You can assign this value to a variable and test it against other Season values:

$favorite = Season::Summer;   if ($favorite == get_current_season()) {     echo "It's my favorite season!"; }

Using type hints, you can limit parameters or return types to a specific enum. This helps avoid a series of errors and makes editing the code easier:

function get_current_season(): Season {     $day = date("z");       if ($day < 59 || $day > 333) return Season::Winter;     if ($day < 151) return Season::Spring;     if ($day < 243) return Season::Summer;     if ($day < 334) return Season::Autumn; }

If the get_current_season function tries to return a value other than Season, PHP will raise a fatal TypeError.

Enums are supported

PHP uses the term 'backed enum' to refer to an enum with values. They can be integers or strings:

enum Month: int {     case Jan = 1;     case Feb = 2;     //. }

You need to declare the supported enum type and it must be int or string. You can access the underlying value using the read-only value property :

echo Month::Jan->value;

When using supported enums, you can also convert them, from their scalar equivalent, using the from method :

var_dump(Month::from(2));

enum methods

PHP enums also have methods, making them a bit like a shortened class. This shows PHP's position, between procedural and object-oriented languages.

For example, you can add this simple method to the Month enum to get the number of days from a specific value:

/* Note: no leap-year handling! */ function daysInMonth(): int {     if ($this == Month::Feb) return 28;     if (in_array($this, array(Month::Apr, Month::Jun, Month::Sep, Month::Nov))) return 30;     return 31; }

Note, you can use $this to refer to a specific enum value, just like you use $this to refer to a certain object. You can also use the standard equality operator, ==, to compare enum values.

Enum also supports static methods. For example:

static function random(): Month {     return Month::from(rand(1, count(Month::cases()))); }

Above are the things you need to know about enums in PHP . Hope this article is useful to you.

5 ★ | 1 Vote

May be interested

  • 10 tips to help you become a great Pokemon trainer10 tips to help you become a great Pokemon trainer
    in the article below, tipsmake.com will introduce to you some tips to easily become a great trainer in this pokemon go game offline ...
  • How to use GoChat application in Pokémon GOHow to use GoChat application in Pokémon GO
    pokémon go has become a very hot phenomenon since its debut. any information or tricks related to the game are read and applied by players during the process of catching pokémon. and the gochat chat app for pokémon go players brings space to capture pokémon much more interesting.
  • How to play Pokemon GO in Landscape Mode on the iPhoneHow to play Pokemon GO in Landscape Mode on the iPhone
    although players can play pokemon go in portrait mode. however, if you want to watch and play games on a large and eye-catching screen, players can switch to playing games in landscape mode.
  • The secret to controlling Pokemon Go employees at workThe secret to controlling Pokemon Go employees at work
    these days, hr managers are faced with an extremely painful problem that is the status of priority employees playing pokemon go more than work. this has caused a small impact on productivity and efficiency.
  • Check out the 'buffalo' Pokémon in Pokémon GoCheck out the 'buffalo' Pokémon in Pokémon Go
    each type of pokemon has hp, cp, ability to attack and endure differently. based on these indicators, players can determine as well as choosing the most powerful pokemon for their offensive tactics.
  • Sitting home can also locate Pokemon around, do you believe it?Sitting home can also locate Pokemon around, do you believe it?
    the tightening of the niantic developers' rules to prevent players from abusing the support tools also brings annoyance, such as those who have no conditions to move much, go away, it is hard to know. get the location of the pokemon around the area they live in
  • 5 undeniable benefits when playing Pokemon Go5 undeniable benefits when playing Pokemon Go
    get to know many new people, breathe fresh air, relieve stress, increase concentration thanks to going out for a walk .... are compelling reasons to force you to try pokemon go now .
  • Want to earn the fastest Pokécoins in Pokémon Go? So don't miss this article!Want to earn the fastest Pokécoins in Pokémon Go?  So don't miss this article!
    pokécoins in pokémon go play the role of buying items in the store. the more coins you earn, the more likely you are to buy more items. to earn pokécoins, players will have to complete certain tasks or buy real money.
  • Pokémon systems when fighting in Pokémon GoPokémon systems when fighting in Pokémon Go
    each pokémon system in pokémon go has different strengths, along with a specific weakness. this type of pokémon will have the power to attack the other pokémon, but can defeat the other pokémon. if you know the characteristics of each type, it will be easier to choose which pokémon to battle.
  • The terms you need to know when playing Pokémon GoThe terms you need to know when playing Pokémon Go
    pokémon go is the most prominent name in recent days. this game of capturing and training virtual animals has created a relatively new way of playing, as players have to constantly move to catch pokémon. during the process of joining pokémon go, you will encounter and use a lot of important terms. so what do they mean?