| 1 | <?php declare(strict_types=1); |
||
| 18 | class Item extends Node implements ItemInterface |
||
| 19 | { |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var \ArrayIterator |
||
| 23 | */ |
||
| 24 | protected $medias; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @var AuthorInterface |
||
| 28 | */ |
||
| 29 | protected $author; |
||
| 30 | |||
| 31 | 93 | public function __construct() |
|
| 37 | |||
| 38 | /** |
||
| 39 | * @param MediaInterface $media |
||
| 40 | * @return ItemInterface |
||
| 41 | */ |
||
| 42 | 11 | public function addMedia(MediaInterface $media) : ItemInterface |
|
| 48 | |||
| 49 | /** |
||
| 50 | * @return iterable |
||
| 51 | */ |
||
| 52 | 12 | public function getMedias() : iterable |
|
| 56 | |||
| 57 | /** |
||
| 58 | * @return boolean |
||
| 59 | */ |
||
| 60 | 12 | public function hasMedia() : bool |
|
| 64 | |||
| 65 | /** |
||
| 66 | * @return MediaInterface |
||
| 67 | */ |
||
| 68 | 6 | public function newMedia() : MediaInterface |
|
| 72 | |||
| 73 | /** |
||
| 74 | * @return AuthorInterface |
||
| 75 | */ |
||
| 76 | 11 | public function getAuthor() : ? AuthorInterface |
|
| 80 | |||
| 81 | /** |
||
| 82 | * @param AuthorInterface $author |
||
| 83 | * @return ItemInterface |
||
| 84 | */ |
||
| 85 | 17 | public function setAuthor(AuthorInterface $author = null) : ItemInterface |
|
| 91 | |||
| 92 | /** |
||
| 93 | * @return AuthorInterface |
||
| 94 | */ |
||
| 95 | 12 | public function newAuthor() : AuthorInterface |
|
| 99 | } |
||
| 100 |
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_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.