Skip to content

Commit b52c2f2

Browse files
committed
Merge pull request #2 from garoevans/patch-1
Add caching to `toArray` method
2 parents 4a27d4e + 067f53e commit b52c2f2

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/MyCLabs/Enum/Enum.php

+12-2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ abstract class Enum
2020
* @var mixed
2121
*/
2222
protected $value;
23+
24+
/**
25+
* Store existing constants in a static cache per object.
26+
* @var array
27+
*/
28+
private static $constantsCache = array();
2329

2430
/**
2531
* Creates a new value of some type
@@ -57,8 +63,12 @@ public function __toString()
5763
*/
5864
public static function toArray()
5965
{
60-
$reflection = new \ReflectionClass(get_called_class());
61-
return $reflection->getConstants();
66+
$calledClass = get_called_class();
67+
if(!array_key_exists($calledClass, self::$constantsCache)) {
68+
$reflection = new \ReflectionClass($calledClass);
69+
self::$constantsCache[$calledClass] = $reflection->getConstants();
70+
}
71+
return self::$constantsCache[$calledClass];
6272
}
6373

6474
/**

0 commit comments

Comments
 (0)