diff --git a/src/Enum.php b/src/Enum.php index 140e722..9f16d60 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -24,6 +24,13 @@ abstract class Enum */ protected $value; + /** + * Enum value instance + * + * @var mixed + */ + protected static $instances = array(); + /** * Store existing constants in a static cache per object. * @@ -177,8 +184,15 @@ public static function search($value) public static function __callStatic($name, $arguments) { $array = static::toArray(); + $class = get_called_class(); if (isset($array[$name])) { - return new static($array[$name]); + if (isset(static::$instances[$class][$name])) { + return static::$instances[$class][$name]; + } else { + $result = new static($array[$name]); + static::$instances[$class][$name] = $result; + return $result; + } } throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class()); diff --git a/tests/EnumTest.php b/tests/EnumTest.php index c468017..9339f0f 100644 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -225,6 +225,17 @@ public function testEquals() $this->assertTrue($foo->equals($anotherFoo)); } + /** + * __callStatic() + */ + public function testSameInstance() + { + $foo1 = EnumFixture::FOO(); + $foo2 = EnumFixture::FOO(); + + $this->assertSame($foo1, $foo2); + } + /** * equals() */