Skip to content

Commit

Permalink
Always return the same instance of a const
Browse files Browse the repository at this point in the history
  • Loading branch information
adrium committed Aug 28, 2017
1 parent 955f570 commit 117abc2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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());
Expand Down
11 changes: 11 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
*/
Expand Down

0 comments on commit 117abc2

Please sign in to comment.