Last active
December 16, 2016 08:00
-
-
Save halaxa/3720043 to your computer and use it in GitHub Desktop.
Type safe enum implementation in PHP
This file contains 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 | |
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