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 string */ | ||
| 16 | private $name; | ||
| 17 | |||
| 18 | /** | ||
| 19 | * @param string $name | ||
| 20 | */ | ||
| 21 | 3 | final private function __construct(string $name) | |
| 25 | |||
| 26 | /** | ||
| 27 | * Creates enum instance by name | ||
| 28 | * | ||
| 29 | * @param string $name | ||
| 30 | * | ||
| 31 | * @return static | ||
| 32 | * | ||
| 33 | * @throws EnumException | ||
| 34 | */ | ||
| 35 | 8 | final public static function createByName(string $name) | |
| 51 | |||
| 52 | /** | ||
| 53 | * Creates enum instance with short static constructor | ||
| 54 | * | ||
| 55 | * @param string $name | ||
| 56 | * @param array $arguments | ||
| 57 | * | ||
| 58 | * @return static | ||
| 59 | * | ||
| 60 | * @throws EnumException | ||
| 61 | */ | ||
| 62 | 7 | final public static function __callStatic(string $name, array $arguments) | |
| 66 | |||
| 67 | 8 | public static function getConstList(): array | |
| 71 | |||
| 72 | 6 | View Code Duplication | private static function getConstantReflection(string $class, string $name): \ReflectionClassConstant | 
| 83 | |||
| 84 | 6 | private static function getConstKey(string $class, string $name): string | |
| 88 | |||
| 89 | 6 | private static function findParentClassForConst(string $name): string | |
| 93 | |||
| 94 | 8 | private static function getEnumReflection(string $class): \ReflectionClass | |
| 108 | |||
| 109 | /** | ||
| 110 | * Create named enum instance | ||
| 111 | * | ||
| 112 | * @param string $name | ||
| 113 | * | ||
| 114 | * @return static | ||
| 115 | */ | ||
| 116 | 6 | View Code Duplication | private static function createNamedInstance(string $name) | 
| 128 | |||
| 129 | 1 | final public function getName(): string | |
| 133 | |||
| 134 | /** | ||
| 135 |      * {@inheritdoc} | ||
| 136 | */ | ||
| 137 | 1 | final public function __toString(): string | |
| 141 | } | ||
| 142 | 
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: