Skip to content

Commit 4ed0a01

Browse files
committed
Add caching to toArray method
Reflection can be slow on occasions and this optimization should be beneficial if `toArray` is being called more than once per request.
1 parent 4a27d4e commit 4ed0a01

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/MyCLabs/Enum/Enum.php

+10-1
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 instantiated reflection objects in a static cache.
26+
* @var array
27+
*/
28+
protected static $reflectionCache = array();
2329

2430
/**
2531
* Creates a new value of some type
@@ -57,7 +63,10 @@ public function __toString()
5763
*/
5864
public static function toArray()
5965
{
60-
$reflection = new \ReflectionClass(get_called_class());
66+
$calledClass = get_called_class();
67+
if(!array_key_exists($calledClass, self::$reflectionCache)) {
68+
self::$reflectionCache[$calledClass] = new \ReflectionClass($calledClass);
69+
}
6170
return $reflection->getConstants();
6271
}
6372

0 commit comments

Comments
 (0)