Explain usage of enumerations in PHP
Explain usage of enumerations in PHP
Here is an explanation of how to use enumerations in PHP:
Enumerations, also known as "enums", are a special data type that allows you to define a set of named constants. They are useful for representing a fixed set of values that have a specific meaning in your application.
In PHP, enumerations were introduced in version 8.1 as part of the Enumerations RFC. They provide a way to define a set of named constants that can be used throughout your code.
To define an enumeration in PHP, you use the enum
keyword followed by the name of the enum. Inside the enum, you define the individual cases using the case
keyword:
enum Color {
case Red;
case Green;
case Blue;
}
Each case represents a named constant within the enum. You can also assign values to the cases:
enum Size: string {
case Small = 'S';
case Medium = 'M';
case Large = 'L';
}
In this example, the Size
enum has string values assigned to each case.
Once you have defined an enum, you can use it in your code by referencing the enum name followed by the case name:
$color = Color::Red;
$size = Size::Medium;
You can also use enums in switch statements:
switch ($color) {
case Color::Red:
echo "The color is red";
break;
case Color::Green:
echo "...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào