Skip to content

Always return the same instance of a const #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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