1 | <?php |
||
18 | abstract class Model |
||
19 | { |
||
20 | protected $mappingClasses = []; |
||
21 | |||
22 | /** |
||
23 | * Contains property name mappings. |
||
24 | * |
||
25 | * [ |
||
26 | * 'data_array_property1' => 'objectProperty1', |
||
27 | * 'data_array_property2' => 'objectProperty2', |
||
28 | * ] |
||
29 | * |
||
30 | * Data array property uses as keys |
||
31 | * because there is can be more then one rule per object property |
||
32 | * |
||
33 | * f.g. $data['nmodels'] and ['modelsnum'] should map in modelsCount property. |
||
34 | * Otherwise not unique array keys cause remapping of properties. |
||
35 | * |
||
36 | * @var array |
||
37 | */ |
||
38 | protected $propNameMap = []; |
||
39 | |||
40 | /** |
||
41 | * Constructor |
||
42 | * |
||
43 | * @param array $data |
||
44 | */ |
||
45 | 174 | public function __construct($data = []) |
|
49 | |||
50 | /** |
||
51 | * Set from array |
||
52 | * |
||
53 | * @param array $data |
||
54 | * @return $this |
||
55 | */ |
||
56 | 172 | public function fromArray($data) |
|
88 | |||
89 | /** |
||
90 | * Set from json |
||
91 | * |
||
92 | * @param string $json |
||
93 | * @return $this |
||
94 | */ |
||
95 | 1 | public function fromJson($json) |
|
100 | |||
101 | /** |
||
102 | * Get array from object |
||
103 | * |
||
104 | * @return array |
||
105 | */ |
||
106 | 43 | public function toArray() |
|
110 | |||
111 | /** |
||
112 | * Get array from object |
||
113 | * |
||
114 | * @return string |
||
115 | */ |
||
116 | 1 | public function toJson() |
|
120 | |||
121 | /** |
||
122 | * Get array from object |
||
123 | * |
||
124 | * @param array|object $data |
||
125 | * @return array |
||
126 | */ |
||
127 | 41 | protected function toArrayRecursive($data) |
|
163 | } |
||
164 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: