From 117abc237f6fa83c313c368b9bd179b46fe9f8c7 Mon Sep 17 00:00:00 2001 From: Adrian Date: Sat, 21 Jan 2017 14:05:13 +0100 Subject: [PATCH] Always return the same instance of a const --- src/Enum.php | 16 +++++++++++++++- tests/EnumTest.php | 11 +++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) 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() */