Last active
May 5, 2021 13:06
-
-
Save Gyvastis/c7119ab9ea60f6ec10b8484771d6846a to your computer and use it in GitHub Desktop.
PHP Enum as Class
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 | |
namespace Earth; | |
class Enum { | |
protected string $constName; | |
public function __construct(string $constName) { | |
$this->constName = $constName; | |
} | |
public function __toString() { | |
try { | |
return self::getConstants()[$this->constName]; | |
} | |
catch(\Throwable $ex) { | |
return 'unknown'; | |
} | |
} | |
public static function equals(Enum $a, Enum $b) { | |
return (string)$a === (string)$b; | |
} | |
public function is(Enum $b) { | |
return (string)$this === (string)$b; | |
} | |
public static function __callStatic($method, $args) { | |
if(in_array($method, array_keys(self::getConstants()))) { | |
$calledClass = self::getClass(); | |
return new $calledClass($method); | |
} | |
throw new \Exception(sprintf("`%s` is not a %s.", $method, get_called_class())); | |
} | |
protected static function getConstants() { | |
return (new \ReflectionClass(self::getClass()))->getConstants(); | |
} | |
protected static function getClass() { | |
return get_called_class(); | |
} | |
} | |
class TemperatureEnum extends Enum { | |
public const COLD = 'cold'; | |
public const HOT = 'hot'; | |
} | |
$cold = TemperatureEnum::COLD(); | |
$hot = TemperatureEnum::HOT(); | |
echo $cold; // echoes "cold" | |
echo $hot; // echoes "hot" | |
//echo TemperatureEnum::Unknown(); // throws "`Unknown` is not a Earth\TemperatureEnum" | |
var_dump([ | |
$cold == $hot, // false | |
$cold == TemperatureEnum::COLD(), // true | |
$cold === TemperatureEnum::COLD(), // false | |
Enum::equals($cold, TemperatureEnum::COLD()), // true | |
$cold->is(TemperatureEnum::COLD()) // true | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment