Skip to content

Instantly share code, notes, and snippets.

@xphere
Created March 9, 2016 12:29
Show Gist options
  • Save xphere/c7106193b49a61eeb0b1 to your computer and use it in GitHub Desktop.
Save xphere/c7106193b49a61eeb0b1 to your computer and use it in GitHub Desktop.
Trait for Enum's in PHP
<?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