| 1 | <?php |
||
| 16 | final class DetectFirstValueTypeCollection extends Collection implements TypeInterface |
||
| 17 | { |
||
| 18 | /** |
||
| 19 | * @var string |
||
| 20 | */ |
||
| 21 | private $getTypeHelper; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param array|Arrayy $data |
||
| 25 | * @param string $iteratorClass |
||
| 26 | * @param bool $checkPropertiesInConstructor |
||
| 27 | * |
||
| 28 | * @psalm-param array<T>|Arrayy $data |
||
| 29 | * @psalm-param class-string<\ArrayIterator> $iteratorClass |
||
| 30 | */ |
||
| 31 | 8 | public function __construct( |
|
| 53 | |||
| 54 | /** |
||
| 55 | * The type (FQCN) associated with this collection. |
||
| 56 | * |
||
| 57 | * @return string |
||
| 58 | */ |
||
| 59 | 8 | public function getType() |
|
| 63 | |||
| 64 | /** |
||
| 65 | * @param mixed $value |
||
| 66 | * |
||
| 67 | * @return string |
||
| 68 | * |
||
| 69 | * @psalm-param T $value |
||
| 70 | */ |
||
| 71 | 8 | private function getTypeFromFirstValue($value): string |
|
| 75 | } |
||
| 76 |
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.