1 | <?php |
||
11 | final class None extends AbstractOptional |
||
12 | { |
||
13 | /** |
||
14 | * @var None |
||
15 | */ |
||
16 | private static $instance; |
||
17 | |||
18 | /** |
||
19 | * None constructor. |
||
20 | */ |
||
21 | private function __construct() |
||
24 | |||
25 | /** |
||
26 | * |
||
27 | */ |
||
28 | private function __clone() |
||
31 | |||
32 | /** |
||
33 | * @return None |
||
34 | */ |
||
35 | public static function instance(): self |
||
43 | |||
44 | /** |
||
45 | * @param mixed $value |
||
46 | * |
||
47 | * @return bool |
||
48 | */ |
||
49 | public function isSome(&$value = null): bool |
||
55 | |||
56 | /** |
||
57 | * @throws Exception |
||
58 | */ |
||
59 | public function unwrap() |
||
63 | |||
64 | /** |
||
65 | * @param callable $callback |
||
66 | * |
||
67 | * @return OptionalInterface |
||
68 | */ |
||
69 | public function ensure(callable $callback): OptionalInterface |
||
73 | |||
74 | /** |
||
75 | * @param $value |
||
76 | * |
||
77 | * @return bool |
||
78 | */ |
||
79 | public function isEqualTo($value): bool |
||
83 | |||
84 | /** |
||
85 | * @param $value |
||
86 | * |
||
87 | * @return bool |
||
88 | */ |
||
89 | public function isIdenticalTo($value): bool |
||
93 | } |
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.