Skip to content

Commit 117abc2

Browse files
committed
Always return the same instance of a const
1 parent 955f570 commit 117abc2

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Enum.php

+15-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ abstract class Enum
2424
*/
2525
protected $value;
2626

27+
/**
28+
* Enum value instance
29+
*
30+
* @var mixed
31+
*/
32+
protected static $instances = array();
33+
2734
/**
2835
* Store existing constants in a static cache per object.
2936
*
@@ -177,8 +184,15 @@ public static function search($value)
177184
public static function __callStatic($name, $arguments)
178185
{
179186
$array = static::toArray();
187+
$class = get_called_class();
180188
if (isset($array[$name])) {
181-
return new static($array[$name]);
189+
if (isset(static::$instances[$class][$name])) {
190+
return static::$instances[$class][$name];
191+
} else {
192+
$result = new static($array[$name]);
193+
static::$instances[$class][$name] = $result;
194+
return $result;
195+
}
182196
}
183197

184198
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class());

tests/EnumTest.php

+11
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,17 @@ public function testEquals()
225225
$this->assertTrue($foo->equals($anotherFoo));
226226
}
227227

228+
/**
229+
* __callStatic()
230+
*/
231+
public function testSameInstance()
232+
{
233+
$foo1 = EnumFixture::FOO();
234+
$foo2 = EnumFixture::FOO();
235+
236+
$this->assertSame($foo1, $foo2);
237+
}
238+
228239
/**
229240
* equals()
230241
*/

0 commit comments

Comments
 (0)