0
0
PHPprogramming~30 mins

Enums in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Working with Enums in PHP
📖 Scenario: You are building a simple system to manage user roles in a web application. Each user can have a role like Admin, Editor, or Viewer. Using enums helps keep these roles organized and easy to manage.
🎯 Goal: Create a PHP enum called UserRole with specific roles, then write code to check a user's role and print a message.
📋 What You'll Learn
Create a backed enum called UserRole with string values for Admin, Editor, and Viewer.
Create a variable called currentUserRole and assign it the UserRole::Editor value.
Write a match expression to print a message based on the currentUserRole.
Print the message to the screen.
💡 Why This Matters
🌍 Real World
Enums help organize fixed sets of related values like user roles, making code easier to read and less error-prone.
💼 Career
Understanding enums is useful for backend PHP development, especially in frameworks and applications that manage user permissions or states.
Progress0 / 4 steps
1
Create the UserRole enum
Create a backed enum called UserRole with string values: Admin = 'admin', Editor = 'editor', and Viewer = 'viewer'.
PHP
Need a hint?

Use the enum keyword followed by the name UserRole and specify : string for backed enum. Then add case lines for each role.

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

Use the enum name UserRole followed by ::Editor to assign the enum value to the variable.

3
Use match to create a message based on the role
Write a match expression that uses $currentUserRole to set a variable $message with these exact strings:
UserRole::Admin => "You have full access.",
UserRole::Editor => "You can edit content.",
UserRole::Viewer => "You can view content."
PHP
Need a hint?

Use the match expression with $currentUserRole and assign the result to $message. Match each enum case to the exact string.

4
Print the message
Write a print statement to display the $message variable.
PHP
Need a hint?

Use print($message); to show the message on the screen.