1 | <?php declare(strict_types=1); |
||
16 | class Element implements ElementInterface, ElementsAwareInterface |
||
17 | { |
||
18 | use ElementsAwareTrait; |
||
19 | |||
20 | /** |
||
21 | * @var string |
||
22 | */ |
||
23 | protected $name; |
||
24 | |||
25 | /** |
||
26 | * @var string |
||
27 | */ |
||
28 | protected $value; |
||
29 | |||
30 | /** |
||
31 | * @var array |
||
32 | */ |
||
33 | protected $attributes = array(); |
||
34 | |||
35 | 37 | public function __construct() |
|
39 | |||
40 | /** |
||
41 | * @return string |
||
42 | */ |
||
43 | 24 | public function getName() : string |
|
47 | |||
48 | /** |
||
49 | * @param string $name |
||
50 | * @return ElementInterface |
||
51 | */ |
||
52 | 33 | public function setName(string $name) : ElementInterface |
|
58 | |||
59 | /** |
||
60 | * @return string |
||
61 | */ |
||
62 | 15 | public function getValue() : ? string |
|
66 | |||
67 | /** |
||
68 | * @param string $value |
||
69 | * @return ElementInterface |
||
70 | */ |
||
71 | 28 | public function setValue(string $value = null) : ElementInterface |
|
77 | |||
78 | /** |
||
79 | * @param string $name |
||
80 | * @return null|string |
||
81 | */ |
||
82 | 3 | public function getAttribute(string $name) : ? string |
|
90 | |||
91 | /** |
||
92 | * @return iterable |
||
93 | */ |
||
94 | 7 | public function getAttributes() : iterable |
|
98 | |||
99 | /** |
||
100 | * @param string $name |
||
101 | * @param string $value |
||
102 | * @return ElementInterface |
||
103 | */ |
||
104 | 5 | public function setAttribute(string $name, string $value = null) : ElementInterface |
|
110 | } |
||
111 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.