1 | <?php |
||
12 | class Handler { |
||
13 | /** |
||
14 | * Actual handler |
||
15 | * |
||
16 | * @var callable|array|null |
||
17 | */ |
||
18 | protected $handler = null; |
||
19 | |||
20 | /** |
||
21 | * Constructor |
||
22 | * |
||
23 | * @param string|callable $handler |
||
24 | */ |
||
25 | public function __construct( $handler ) { |
||
28 | |||
29 | /** |
||
30 | * Parse a handler to a callable or a [class, method] array |
||
31 | * |
||
32 | * @param string|callable $handler |
||
33 | * @return callable|array|null |
||
34 | */ |
||
35 | protected function parse( $handler ) { |
||
46 | |||
47 | /** |
||
48 | * Parse a string handler to a callable or a [class, method] array |
||
49 | * |
||
50 | * @param string $handler |
||
51 | * @return callable|array|null |
||
52 | */ |
||
53 | protected function parseFromString( $handler ) { |
||
68 | |||
69 | /** |
||
70 | * Execute the handler returning raw result |
||
71 | * |
||
72 | * @return string|array|\Psr\Http\Message\ResponseInterface |
||
73 | */ |
||
74 | protected function executeHandler() { |
||
86 | |||
87 | /** |
||
88 | * Set the handler |
||
89 | * |
||
90 | * @param string|callable $new_handler |
||
91 | * @return null |
||
92 | */ |
||
93 | public function set( $new_handler ) { |
||
102 | |||
103 | /** |
||
104 | * Execute the handler |
||
105 | * |
||
106 | * @return \Psr\Http\Message\ResponseInterface |
||
107 | */ |
||
108 | public function execute() { |
||
121 | } |
||
122 |
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.