Iterable objects and array type hinting?

前端 未结 6 1574
遇见更好的自我
遇见更好的自我 2020-11-30 03:28

I have a lot of functions that either have type hinting for arrays or use is_array() to check the array-ness of a variable.

Now I\'m starting to use ob

6条回答
  •  执笔经年
    2020-11-30 04:16

    PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

    This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

    iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

    function foo(iterable $iterable) {
        foreach ($iterable as $value) {
            // ...
        }
    }
    

    This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

    var_dump(is_iterable([1, 2, 3])); // bool(true)
    var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
    var_dump(is_iterable((function () { yield 1; })())); // bool(true)
    var_dump(is_iterable(1)); // bool(false)
    var_dump(is_iterable(new stdClass())); // bool(false)
    

提交回复
热议问题