- Edited
<?php
enum Food {
case Hotdog;
case Fish;
case Steak;
case Salad;
}
function eating(Food $type)
{
echo "I like $type";
}
?>
<?php
enum Food {
case Hotdog;
case Fish;
case Steak;
case Salad;
}
function eating(Food $type)
{
echo "I like $type";
}
?>
Do you have a question, problem, or error that you need help with?
Did you try calling the eating(...) function with an input that's an instance of the Food enum? Did you examine the php documentation for this so that you would know you have to reference the ->name property of the Food enum in order to access the corresponding case name?
Hadn't looked at the new enum
stuff until I saw this, then had to play around with it. I got this to work, though no idea if it's "good":
enum Food
{
case Hotdog;
case Fish;
case Steak;
case Salad;
public function get(): string {
return $this->name;
}
}
function eating(Food $type) {
echo "I like eating ".$type->get()."\n";
}
foreach(['Hotdog', 'Fish', 'Steak', 'Salad', 'Error'] as $test) {
$food = constant("Food::{$test}");
eating($food);
}
Output:
I like eating Hotdog
I like eating Fish
I like eating Steak
I like eating Salad
PHP Warning: Uncaught Error: Undefined constant Food::Error in php shell code:2
Stack trace:
#0 php shell code(2): constant('Food::Error')
#1 {main}
thrown in php shell code on line 2