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:

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.

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:

$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

junior

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

entry

What is the use of ini_set() ?

middle

What is the difference between a PHP interpreter and a PHP handler?

junior

Is there a difference between isset and !empty ?

Bình luận

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

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