1 | <?php |
||
9 | abstract class Enum |
||
10 | { |
||
11 | private $scalar; |
||
12 | private static $cache = array(); |
||
13 | |||
14 | 3 | function __construct($value) |
|
|
|||
15 | { |
||
16 | 3 | $ref = new \ReflectionObject($this); |
|
17 | 3 | $consts = $ref->getConstants(); |
|
18 | 3 | if (! in_array($value, $consts, true)) { |
|
19 | 1 | throw new \InvalidArgumentException( |
|
20 | 1 | 'value must be ' . implode(',', $consts) . ". but $value passed." |
|
21 | 1 | ); |
|
22 | } |
||
23 | 2 | $this->scalar = $value; |
|
24 | 2 | } |
|
25 | |||
26 | 1 | final static function __callStatic($name, $args) |
|
27 | { |
||
28 | 1 | $class = get_called_class(); |
|
29 | 1 | $constantName = "$class::$name"; |
|
30 | 1 | if (isset(self::$cache[$constantName])) { |
|
31 | 1 | return self::$cache[$constantName]; |
|
32 | } else { |
||
33 | 1 | $const = constant($constantName); |
|
34 | 1 | return self::$cache[$constantName] = new $class($const); |
|
35 | } |
||
36 | } |
||
37 | |||
38 | 2 | final function valueOf() |
|
42 | |||
43 | 2 | final function __toString() |
|
47 | } |
||
48 |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.