On 11/01/2017 11:31 PM, Michael Morris wrote:
> Drupal 8 accomplishes this through assert() and a helper class.
>
> function foo ( array $a ) {
>   assert( Inspector::assertAllStrings( $a ));
> }
>
> This could be improved by having an collectionof operator similar to the
> instanceof operator.
>
> function ( array $a ) {
>   assert( $a collectionof string );
> }
>
> I say "collectionof" because while arrays are the most common traversable
> objects, they aren't the only ones.  The above approach, combined with the
> existing assert structure, can provide the dev time checking of the code
> while in under development, and it can be turned off in production. Or it
> can be used outside of assert to be checked at all times.
>
> Since this invokes a new keyword I think that would mean this solution
> would be PHP 8.
>
> Brackets might be used with instance of to notify it to traverse down one
> level maybe??
>
> function ( array $a ) {
>   assert( $a instanceof [string] );
> }
>
> This avoids any BC issues, but it looks odd.  Not as odd as \ for a
> namespace operation :P  But odd.

While I normally strongly agree with supporting all traversables, not
just arrays, in this case I don't think it works.  The whole point of
using a traversable is that you don't have all of the values up front. 
If you did... you'd just have an array.  So checking "all values" of a
traversable in one point in time is a destructive operation as it runs
out the iterator, which if it's an infinite iterator could, erm, be bad.

Rather, arrays can/should be checked at once (as above), whereas a
traversable should be able to declare that it only returns a given type,
and if it ever tries to return a different type then the traversable
itself type-errors.

--Larry Garfield

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to