Skip to content

Instantly share code, notes, and snippets.

@elminson
Forked from masterfermin02/GradeEnum.php
Created June 16, 2023 04:23
Show Gist options
  • Save elminson/3aa15d2a449ec9c7a19c7a369fe460f2 to your computer and use it in GitHub Desktop.
Save elminson/3aa15d2a449ec9c7a19c7a369fe460f2 to your computer and use it in GitHub Desktop.
<?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