Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 7 | abstract class Enum |
||
| 8 | { |
||
| 9 | /** @var Enum[] */ |
||
| 10 | private static $instances = []; |
||
| 11 | /** @var \ReflectionClassConstant[] */ |
||
| 12 | private static $constReflections = []; |
||
| 13 | /** @var \ReflectionClass[] */ |
||
| 14 | private static $reflections = []; |
||
| 15 | /** @var mixed */ |
||
| 16 | private $value; |
||
| 17 | /** @var string */ |
||
| 18 | private $name; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @param string $name |
||
| 22 | * @param mixed $value |
||
| 23 | */ |
||
| 24 | 3 | final private function __construct(string $name, $value) |
|
| 29 | |||
| 30 | /** |
||
| 31 | * Creates enum instance with short static constructor |
||
| 32 | * |
||
| 33 | * @param string $name |
||
| 34 | * @param array $arguments |
||
| 35 | * |
||
| 36 | * @return static |
||
| 37 | * |
||
| 38 | * @throws \BadMethodCallException |
||
| 39 | * @throws EnumException |
||
| 40 | */ |
||
| 41 | 6 | final public static function __callStatic(string $name, array $arguments) |
|
| 51 | |||
| 52 | 5 | View Code Duplication | private static function getConstantReflection(string $class, string $name): \ReflectionClassConstant |
| 63 | |||
| 64 | 5 | private static function getConstKey(string $class, string $name): string |
|
| 68 | |||
| 69 | 5 | private static function findParentClassForConst(string $name): string |
|
| 73 | |||
| 74 | 6 | private static function getConstList(): array |
|
| 78 | |||
| 79 | 6 | private static function getEnumReflection(string $class): \ReflectionClass |
|
| 87 | |||
| 88 | /** |
||
| 89 | * Create named enum instance |
||
| 90 | * |
||
| 91 | * @param string $name |
||
| 92 | * @param mixed $value |
||
| 93 | * |
||
| 94 | * @return static |
||
| 95 | */ |
||
| 96 | 5 | View Code Duplication | private static function createNamedInstance(string $name, $value) |
| 108 | |||
| 109 | /** |
||
| 110 | * @return mixed |
||
| 111 | */ |
||
| 112 | 1 | final public function getValue() |
|
| 116 | |||
| 117 | 1 | final public function getName(): string |
|
| 121 | |||
| 122 | /** |
||
| 123 | * {@inheritdoc} |
||
| 124 | */ |
||
| 125 | 1 | public function __toString(): string |
|
| 129 | } |
||
| 130 |
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClassto useselfinstead: