1
| enum Color {Red, Green, Blue}
|
1 2 3 4 5 6
| var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; })(Color || (Color = {}));
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var color;
var setColorEnum = function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; }
if(Color || (Color = {})){ Color["Red"] = 0; Color[Color["Red"]] = "Red"; }
|
由于php中直接声明的变量obj是obj,array是array。所以需要先创建一个enum类实现array接口这样就可以实现与上述代码相同的赋值行为。代码如下
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
| <?php
class enum implements ArrayAccess { private $container = array(); public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } public function offsetExists($offset) { return isset($this->container[$offset]); } public function offsetUnset($offset) { unset($this->container[$offset]); } public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } }
$Color;
(function ($Color) { $Color[$Color->Red = 0] = "Red"; $Color[$Color->Green = 1] = "Green"; $Color[$Color->Blue = 2] = "Blue"; })(($Color = new enum()));
var_dump($Color); var_dump($Color->Red); var_dump($Color->Green); var_dump($Color->Blue); var_dump($Color[0]); var_dump($Color[1]); var_dump($Color[2]);
|
终端输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| object(enum)#2 (4) { ["container":"enum":private]=> array(3) { [0]=> string(3) "Red" [1]=> string(5) "Green" [2]=> string(4) "Blue" } ["Red"]=> int(0) ["Green"]=> int(1) ["Blue"]=> int(2) } int(0) int(1) int(2) string(3) "Red" string(5) "Green" string(4) "Blue"
|