Last active
June 16, 2023 04:23
-
-
Save masterfermin02/ebe1a7a3ef279f8a80ec552a61f96849 to your computer and use it in GitHub Desktop.
This file contains hidden or 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