1 | <?php |
||
7 | abstract class AbstractApiProblem implements ApiProblemInterface |
||
8 | { |
||
9 | /** |
||
10 | * @var string |
||
11 | */ |
||
12 | private $title; |
||
13 | |||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | private $detail; |
||
18 | |||
19 | /** |
||
20 | * @var string|null |
||
21 | */ |
||
22 | private $instance; |
||
23 | |||
24 | /** |
||
25 | * @param string $title |
||
26 | */ |
||
27 | 2 | public function __construct(string $title) |
|
31 | |||
32 | /** |
||
33 | * @param string $title |
||
34 | * |
||
35 | * @return ApiProblemInterface |
||
36 | */ |
||
37 | 1 | public function withTitle(string $title): ApiProblemInterface |
|
44 | |||
45 | /** |
||
46 | * @return string |
||
47 | */ |
||
48 | 2 | public function getTitle(): string |
|
52 | |||
53 | /** |
||
54 | * @param string|null $detail |
||
55 | * |
||
56 | * @return ApiProblemInterface |
||
57 | */ |
||
58 | 1 | public function withDetail(string $detail = null): ApiProblemInterface |
|
65 | |||
66 | /** |
||
67 | * @return string|null |
||
68 | */ |
||
69 | 2 | public function getDetail() |
|
73 | |||
74 | /** |
||
75 | * @param string|null $instance |
||
76 | * |
||
77 | * @return ApiProblemInterface |
||
78 | */ |
||
79 | 1 | public function withInstance(string $instance = null): ApiProblemInterface |
|
86 | |||
87 | /** |
||
88 | * @return string|null |
||
89 | */ |
||
90 | 2 | public function getInstance() |
|
94 | } |
||
95 |
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.