Created
March 9, 2016 12:29
-
-
Save xphere/c7106193b49a61eeb0b1 to your computer and use it in GitHub Desktop.
Trait for Enum's in PHP
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 | |
trait Enum | |
{ | |
private $value; | |
private function __construct($value) | |
{ | |
static $constants; | |
if (null === $constants) { | |
$rc = new \ReflectionClass(self::class); | |
$constants = $rc->getConstants(); | |
} | |
if (!array_key_exists($value, $constants)) { | |
$expected = implode('", "', array_keys($constants)); | |
throw new \RuntimeException(sprintf('Unexpected value "%s", expected "%s"', $value, $expected)); | |
} | |
$this->value = $value; | |
} | |
static public function __callStatic($name, $arguments) | |
{ | |
return new self($name); | |
} | |
public function value() | |
{ | |
return $this->value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment