@@ -17,7 +17,12 @@ abstract class Enum
17
17
/**
18
18
* @var array
19
19
*/
20
- protected static $ _cache = [];
20
+ protected static $ _cacheItems = [];
21
+
22
+ /**
23
+ * @var array
24
+ */
25
+ protected static $ _cacheInstances = [];
21
26
22
27
/**
23
28
* @var int|string
@@ -44,6 +49,22 @@ public function __construct($id)
44
49
}
45
50
}
46
51
52
+ /**
53
+ * @param int|string $id
54
+ * @return static
55
+ * @throws ReflectionException
56
+ * @throws UnexpectedValueException
57
+ * @since 2.1.0
58
+ */
59
+ public static function get ($ id )
60
+ {
61
+ $ key = get_called_class () . '~ ' . $ id ;
62
+ if (empty (static ::$ _cacheInstances [$ key ])) {
63
+ static ::$ _cacheInstances [$ key ] = new static ($ id );
64
+ }
65
+ return static ::$ _cacheInstances [$ key ];
66
+ }
67
+
47
68
/**
48
69
* Проверяет входит ли значение в допустимые
49
70
* @param int|string $id
@@ -65,7 +86,7 @@ public static function isValid($id, array $filter = [])
65
86
public static function toArray (array $ filter = [])
66
87
{
67
88
$ class = get_called_class ();
68
- if (!array_key_exists ($ class , static ::$ _cache )) {
89
+ if (!array_key_exists ($ class , static ::$ _cacheItems )) {
69
90
$ reflection = new \ReflectionClass ($ class );
70
91
if (is_callable ([$ class , 'items ' ])) {
71
92
/** @noinspection PhpUndefinedMethodInspection */
@@ -82,9 +103,9 @@ public static function toArray(array $filter = [])
82
103
}
83
104
$ items [$ constant ]['id ' ] = $ constant ;
84
105
}
85
- static ::$ _cache [$ class ] = $ items ;
106
+ static ::$ _cacheItems [$ class ] = $ items ;
86
107
}
87
- $ items = array_filter (static ::$ _cache [$ class ], function ($ item ) use ($ filter ) {
108
+ $ items = array_filter (static ::$ _cacheItems [$ class ], function ($ item ) use ($ filter ) {
88
109
foreach ($ filter as $ key => $ filterItem ) {
89
110
if (is_int ($ key )) {
90
111
list ($ operator , $ key , $ value ) = $ filterItem ;
@@ -181,7 +202,7 @@ public static function toObjects(array $filter = [])
181
202
{
182
203
$ objects = [];
183
204
foreach (static ::toIds ($ filter ) as $ id ) {
184
- $ objects [$ id ] = new static ($ id );
205
+ $ objects [$ id ] = static :: get ($ id );
185
206
}
186
207
return $ objects ;
187
208
}
0 commit comments