Câu hỏi phỏng vấn PHP
Câu hỏi

Explain usage of enumerations in PHP

Câu trả lời

Here is an explanation of how to use enumerations in PHP:

What are Enumerations?

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.

Defining Enumerations

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:

php Copy
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:

php Copy
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.

Using Enumerations

Once you have defined an enum, you can use it in your code by referencing the enum name followed by the case name:

php Copy
$color = Color::Red;
$size = Size::Medium;

You can also use enums in switch statements:

php Copy
switch ($color) {
    case Color::Red:
        echo "The color is red";
        break;
    case Color::Green:
        echo "...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

Maximum how many arguments are allowed in a function in PHP?

middle

Is there a function to make a copy of a PHP array to another?

senior

Store an array as JSON or as a PHP serialized array?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào