-
-
Save elminson/3aa15d2a449ec9c7a19c7a369fe460f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
enum Grade: string | |
{ | |
case PASS = 'pass'; | |
case FAIL = 'fail'; | |
case A = 'A'; | |
case F = 'F'; | |
case INVALID = 'Invalid grade!\n'; | |
public function message(): string | |
{ | |
return match ($this) { | |
Grade::PASS => 'Passed in', | |
Grade::FAIL => 'Failed in', | |
Grade::A => 'Excellent', | |
Grade::F => 'You can do better', | |
Grade::INVALID => 'Invalid grade!\n', | |
}; | |
} | |
} | |
class GradeEnum | |
{ | |
/** | |
* @param $grade | |
* @param $subject | |
* | |
* @return string | |
*/ | |
public function getGradeRemark(string $grade, string $subject = ''): string | |
{ | |
if ($message = Grade::tryFrom($grade)) { | |
return $message->message() . " $subject!\n"; | |
} | |
return Grade::INVALID->value; | |
} | |
} | |
// Required PHP version 8.1 | |
$grade = new GradeEnum(); | |
echo $grade->getGradeRemark('A'); | |
#Excellent! | |
echo $grade->getGradeRemark('fail', 'English'); | |
#Failed in English! | |
echo $grade->getGradeRemark('faisds', 'English'); | |
#Invalid grade!! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment