PHP Traversable type hint

前端 未结 4 1645
-上瘾入骨i
-上瘾入骨i 2021-01-03 23:15

I have a relatively simple function which uses a foreach

function foo($t) {
     $result;
     foreach($t as $val) {
         $result = dosometh         


        
4条回答
  •  滥情空心
    2021-01-03 23:41

    There is a bug about this: #41942. Closed as 'not a bug'. As PHP arrays are not objects they cannot implement an interface and a such there is no way to type hint both array and Traversable.

    You can use iterator_to_array, ArrayIterator or omit the type hint. Note that iterator_to_array will copy the whole iterator into an array an might thus be inefficient.

    // These functions are functionally equivalent but do not all accept the same arguments
    function foo(array $a) { foobar($a); }
    function bar(Traversable $a) { foobar($a); }
    function foobar($a) {
        foreach($a as $key => $value) {
        }
    }
    
    $array = array(1,2,3)
    $traversable = new MyTraversableObject();
    
    foo($array);
    foo(iterator_to_array($traversable));
    
    bar(new ArrayIterator($array));
    bar($traversable);
    
    foobar($array);
    foobar($traversable);
    

提交回复
热议问题