Challenge - 5 Problems
PHP Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of backed enum value access
What is the output of this PHP code using backed enums?
PHP
<?php
enum Status: string {
case Pending = 'pending';
case Completed = 'completed';
}
echo Status::Completed->value;
Attempts:
2 left
💡 Hint
Access the string value of the enum case using ->value.
✗ Incorrect
Backed enums in PHP allow each case to have a scalar value. Accessing ->value returns that scalar, here 'completed'.
❓ Predict Output
intermediate2:00remaining
Output of enum method call
What does this PHP code print when calling a method inside an enum?
PHP
<?php
enum Direction {
case North;
case South;
case East;
case West;
public function opposite(): Direction {
return match($this) {
Direction::North => Direction::South,
Direction::South => Direction::North,
Direction::East => Direction::West,
Direction::West => Direction::East,
};
}
}
echo Direction::East->opposite()->name;
Attempts:
2 left
💡 Hint
The opposite of East is West according to the match expression.
✗ Incorrect
The method opposite() returns the enum case opposite to the current one. East's opposite is West, so it prints 'West'.
🔧 Debug
advanced2:00remaining
Identify the error in enum declaration
What error does this PHP code raise when declaring this enum?
PHP
<?php
enum Color {
case Red = 1;
case Green = 'green';
case Blue = 3;
}
Attempts:
2 left
💡 Hint
Backed enums require all cases to have the same scalar type.
✗ Incorrect
Backed enums must have all cases with the same scalar type (all int or all string). Mixing int and string causes a fatal error.
📝 Syntax
advanced2:00remaining
Which option causes a syntax error?
Which of these enum declarations will cause a syntax error in PHP?
Attempts:
2 left
💡 Hint
Check for missing semicolons after case declarations.
✗ Incorrect
Option C misses a semicolon after 'case Inactive', causing a syntax error.
🚀 Application
expert2:00remaining
Number of cases in a backed enum
Given this backed enum, how many cases does it contain?
PHP
<?php
enum HttpStatus: int {
case OK = 200;
case Created = 201;
case Accepted = 202;
case NoContent = 204;
}
$cases = HttpStatus::cases();
echo count($cases);
Attempts:
2 left
💡 Hint
Count the number of case declarations inside the enum.
✗ Incorrect
The enum defines 4 cases: OK, Created, Accepted, NoContent. The count of cases() returns 4.