1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| <?php
abstract class Enum { protected $value;
protected static $enumList = [];
public function __construct($enum) { $enumClassName = get_called_class(); if (isset(self::$enumList[$enumClassName])) { $enumList = self::$enumList[$enumClassName]; } else { $objClass = new \ReflectionClass($enumClassName); $enumList = $objClass->getConstants(); self::$enumList[$enumClassName] = $enumList; } if (!in_array($enum, $enumList, true)) { throw new Exception('Error Type'); } $this->value = $enum; }
public function __set($name, $value) { if ($name === 'value') { $enumClassName = get_called_class(); if (!in_array($value, self::$enumList[$enumClassName], true)) { throw new Exception('Error Value'); } $this->value = $value; } else { throw new Exception('Error Type'); } }
public function __get($name) { if ($name === 'value') { return $this->value; } else { throw new Exception('Error Type'); } }
public function __invoke($enum) { $enumClassName = get_called_class(); if (!in_array($enum, self::$enumList[$enumClassName], true)) { throw new Exception('Error Value'); } $this->value = $enum; } }
class Day extends Enum { const MON = 'MON'; const TUE = 'TUE'; const WED = 'WED'; const THU = 'THU'; const FRI = 'FRI'; const SAT = 'SAT'; const SUN = 'SUN '; }
$day = new Day(Day::FRI);
echo $day->value;
try{ $day->value = Day::MON; } catch(Exception $e){ var_dump($e); }
try{ $day->value = 'nihao'; } catch(Exception $e){ var_dump($e->getMessage()); }
|