> How is type checking a bad design?
>
> Between:
>
> function (array $foos) {
> foreach ($foos as $foo) {
> if (! $foo instanceof Foo) {
> throw new InvalidArgumentException("...");
> }
> $foo->bar();
> }
> }
>
> and:
>
> function (array $foos) {
> foreach ($foos as $foo) {
> $foo->bar(); // BOOM, fatal error if not correct object given
> }
> }
>
> which one is worse?
You got me wrong, I don't think that type checking as such is bad but type checking in the way
the RFC promotes it is bad design IMO. If I expect an array with members of a certain type
(regardless if including null or not) then I would not write any of the above code because this is
exactly the bad design I was writing about.
Wouldn't you agree with me that it would be better to type check the entries when they are
added rather than during each function call?
Imagine function foo(Foo[] $foos){} which calls bar and baz which in turn call several other
functions which all have the same type hint Foo[].
The result would be that you have increased your runtime complexity by the factor of function calls.
That's really ugly and I don't think that the language itself should promote such bad
design. If you go further and support multi-dimensional arrays the same way then you would add a
complexity of n*m for each function call with such a type hint.
However, I like the basic idea of the RFC, namely typed arrays. I think a better implementation
would be to introduce that an array holds (visible only internally - could be exposed to userland
later) the defined type and performs the necessary checks during addition and therefore the runtime
complexity for the type hint checks would no longer be linear but constant. Yet, it is probably
better to introduce another internal data structure for this purpose in order that the type hint
"array" does not suffer from the additional checks.
An alternative approach, without changing the language, would be to provide an additional SPL data
structure instead which performs the type check during the addition of an entry.
Nevertheless, the implementation of the RFC as such is not useless. We could introduce a function
is_arrayOf(array $arr, $type, $nullable=false) which could perform the check as implemented in the
pull request (including the nullable option). And I suppose you can come up with valid uses cases
where such a check makes actually sense and worth the new function.