Skip to content

Instantly share code, notes, and snippets.

@Gyvastis
Last active May 5, 2021 13:06
Show Gist options
  • Save Gyvastis/c7119ab9ea60f6ec10b8484771d6846a to your computer and use it in GitHub Desktop.
Save Gyvastis/c7119ab9ea60f6ec10b8484771d6846a to your computer and use it in GitHub Desktop.
PHP Enum as Class
<?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