0
0
PHPprogramming~15 mins

Enum backed values in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Enum backed values
📖 Scenario: You are creating a simple program to represent different user roles in a system. Each role has a specific numeric code that the system uses internally.
🎯 Goal: Build a PHP enum with backed integer values for user roles, then print the numeric code of a specific role.
📋 What You'll Learn
Create a backed enum called UserRole with integer values
Include roles: Admin = 1, Editor = 2, Viewer = 3
Create a variable called role and assign it the UserRole::Editor
Print the integer value of the role variable
💡 Why This Matters
🌍 Real World
Enums with backed values are used in real systems to represent fixed sets of options with specific codes, like user roles, status codes, or categories.
💼 Career
Understanding enums helps you write clearer, safer code that is easier to maintain and less error-prone, a valuable skill for PHP developers.
Progress0 / 4 steps
1
Create the enum UserRole with backed integer values
Write a backed enum called UserRole with these exact entries: Admin = 1, Editor = 2, and Viewer = 3.
PHP
Need a hint?

Use enum UserRole: int and define each case with case Name = value;.

2
Assign the UserRole::Editor to a variable
Create a variable called role and assign it the value UserRole::Editor.
PHP
Need a hint?

Use $role = UserRole::Editor; to assign the enum value.

3
Get the integer value from the enum variable
Create a variable called roleValue and assign it the integer value of $role using the value property.
PHP
Need a hint?

Use $role->value to get the integer value from the enum.

4
Print the integer value of the role
Write a print statement to display the value of $roleValue.
PHP
Need a hint?

Use print($roleValue); to show the number 2.