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 |
||
17 | class guilds extends \Threaded implements \Collectable |
||
18 | { |
||
19 | /** |
||
20 | * @var Message |
||
21 | */ |
||
22 | private $message; |
||
23 | /** |
||
24 | * @var Discord |
||
25 | */ |
||
26 | private $discord; |
||
27 | /** |
||
28 | * @var Logger |
||
29 | */ |
||
30 | private $log; |
||
31 | /** |
||
32 | * @var array |
||
33 | */ |
||
34 | private $channelConfig; |
||
35 | /** |
||
36 | * @var Config |
||
37 | */ |
||
38 | private $config; |
||
39 | /** |
||
40 | * @var Db |
||
41 | */ |
||
42 | private $db; |
||
43 | /** |
||
44 | * @var cURL |
||
45 | */ |
||
46 | private $curl; |
||
47 | /** |
||
48 | * @var Settings |
||
49 | */ |
||
50 | private $settings; |
||
51 | /** |
||
52 | * @var Permissions |
||
53 | */ |
||
54 | private $permissions; |
||
55 | /** |
||
56 | * @var ServerConfig |
||
57 | */ |
||
58 | private $serverConfig; |
||
59 | /** |
||
60 | * @var Users |
||
61 | */ |
||
62 | private $users; |
||
63 | /** |
||
64 | * @var array |
||
65 | */ |
||
66 | private $extras; |
||
67 | |||
68 | View Code Duplication | public function __construct($message, $discord, $channelConfig, $log, $config, $db, $curl, $settings, $permissions, $serverConfig, $users, $extras) |
|
83 | |||
84 | public function run() |
||
100 | } |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: