Skip to content

Instantly share code, notes, and snippets.

@halaxa
Last active December 16, 2016 08:00
Show Gist options
  • Save halaxa/3720043 to your computer and use it in GitHub Desktop.
Save halaxa/3720043 to your computer and use it in GitHub Desktop.
Type safe enum implementation in PHP
<?php
abstract class Enum {
protected $value;
public function getValue()
{
return $this->value;
}
private function __construct($name, $childClass)
{
$constant = "$childClass::$name";
if (defined($constant)) {
$this->value = constant($constant);
} else {
throw new \InvalidStateException($name . ' is not valid option for ' . $childClass);
}
}
public function __toString() {
return $this->value;
}
public static function __callStatic($name, $params)
{
$childClass = get_called_class();
return new $childClass($name, $childClass);
}
}
// Example usage:
class Family extends Enum {
const
FATHER = 'father',
MOTHER = 'mother',
BROTHER = 'brother',
SISTER = 'sister';
}
$member = Family::FATHER();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment