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 | trait HttpErrors |
||
8 | { |
||
9 | |||
10 | public function handle404($data, string $type = 'db', array $page = []) |
||
22 | |||
23 | public function handleApi404($data, string $type = 'db', array $page = []) |
||
35 | |||
36 | View Code Duplication | public function error404() |
|
44 | |||
45 | View Code Duplication | public function error503() |
|
53 | |||
54 | View Code Duplication | public function error500() |
|
62 | |||
63 | /** |
||
64 | * @param null $target |
||
65 | * |
||
66 | * @return mixed |
||
67 | */ |
||
68 | public abstract function redirect($target = null); |
||
69 | |||
70 | /** |
||
71 | * @param string $template |
||
72 | * @param array $params |
||
73 | */ |
||
74 | public abstract function twig(string $template, array $params = []): void; |
||
75 | |||
76 | /** |
||
77 | * @param string $key |
||
78 | * |
||
79 | * @return string|array |
||
80 | */ |
||
81 | public abstract function data(string $key = null); |
||
82 | } |
PHP has two types of connecting operators (logical operators, and boolean operators):
and
&&
or
||
The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like
&&
, or||
.Let’s take a look at a few examples:
Logical Operators are used for Control-Flow
One case where you explicitly want to use logical operators is for control-flow such as this:
Since
die
introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined withthrow
at this point:These limitations lead to logical operators rarely being of use in current PHP code.