0
0
PHPprogramming~5 mins

Enums in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an enum in PHP?
An enum in PHP is a special type that lets you define a set of named values. It helps group related constants together, making code easier to read and safer.
Click to reveal answer
beginner
How do you define a basic enum in PHP?
Use the enum keyword followed by the enum name and a list of cases inside curly braces. For example:<br>
enum Status { case Pending; case Approved; case Rejected; }
Click to reveal answer
intermediate
What is a backed enum in PHP?
A backed enum associates each case with a scalar value like a string or int. This lets you store or compare enum cases easily. Example:<br>
enum Status: string { case Pending = 'pending'; case Approved = 'approved'; }
Click to reveal answer
intermediate
How do you get the scalar value of a backed enum case?
You access the value property of the enum case. For example:<br>
$status = Status::Pending; echo $status->value; // outputs 'pending'
Click to reveal answer
advanced
Can enums in PHP have methods?
Yes! Enums can have methods just like classes. This lets you add behavior related to the enum cases. For example:<br><pre>enum Status { case Pending; case Approved; function label() { return match($this) { self::Pending => 'Waiting', self::Approved => 'Done' }; } }</pre>
Click to reveal answer
Which keyword is used to define an enum in PHP?
Aenum
Bclass
Cinterface
Dconst
What type of values can backed enums have in PHP?
AOnly strings
BOnly integers
CAny data type
DStrings or integers
How do you access the scalar value of a backed enum case?
AUsing the <code>name</code> property
BUsing the <code>value</code> property
CUsing the <code>getValue()</code> method
DUsing the <code>toString()</code> method
Can PHP enums have methods?
AOnly static methods are allowed
BNo, enums cannot have methods
CYes, enums can have methods
DOnly abstract methods are allowed
Which PHP version introduced enums?
APHP 8.1
BPHP 7.4
CPHP 8.0
DPHP 8.2
Explain what enums are in PHP and why they are useful.
Think about how enums help organize fixed sets of values.
You got /3 concepts.
    Describe the difference between pure enums and backed enums in PHP.
    Consider how backed enums store extra information.
    You got /3 concepts.