File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -118,4 +118,26 @@ final public function __toString()
118
118
{
119
119
return (string ) $ this ->value ;
120
120
}
121
+
122
+ /**
123
+ * Instantiate an enum by a name of a constant.
124
+ *
125
+ * This will be called automatically on calling a method
126
+ * with the same name of a defined constant.
127
+ *
128
+ * NOTE: THIS WORKS FOR PHP >= 5.3 ONLY
129
+ *
130
+ * @param string $const The name of the constant to instantiate the enum with
131
+ * @param array $args There should be no arguments
132
+ * @throws BadMethodCallException
133
+ */
134
+ final public static function __callStatic ($ const , array $ args )
135
+ {
136
+ $ class = get_called_class ();
137
+ $ classConst = $ class . ':: ' . $ const ;
138
+ if (!defined ($ classConst )) {
139
+ throw new BadMethodCallException ($ classConst . ' not defined ' );
140
+ }
141
+ return new $ class (constant ($ classConst ));
142
+ }
121
143
}
Original file line number Diff line number Diff line change @@ -88,4 +88,15 @@ public function testConstuctorNonStrictValue()
88
88
$ this ->assertSame (2 , $ enum ->getValue ());
89
89
$ this ->assertSame (1 , $ enum ->getOrdinal ());
90
90
}
91
+
92
+ public function testInstantiateUsingMagicMethod ()
93
+ {
94
+ if (version_compare (PHP_VERSION , '5.3 ' , '< ' )) {
95
+ $ this ->markTestSkipped ("Instantiating using magic method doesn't work for PHP < 5.3 " );
96
+ }
97
+
98
+ $ enum = MabeEnumTest_TestAsset_EnumInheritance::ONE ();
99
+ $ this ->assertInstanceOf ('MabeEnumTest_TestAsset_EnumInheritance ' , $ enum );
100
+ $ this ->assertSame (MabeEnumTest_TestAsset_EnumInheritance::ONE , $ enum ->getValue ());
101
+ }
91
102
}
You can’t perform that action at this time.
0 commit comments