Why must I rewind IteratorIterator

前端 未结 3 1223
心在旅途
心在旅途 2020-12-21 17:01
$arrayIter = new ArrayIterator( array(1, 2) );
$iterIter = new IteratorIterator($arrayIter);

var_dump($iterIter->valid()); //false
var_dump($arrayIter->valid(         


        
3条回答
  •  执念已碎
    2020-12-21 17:27

    Like @johannes said, the position isn't initialized in the IteratorIterator and thus it is not valid before any other of it's methods are run on it or it is used with foreach()

    Try to do

    var_dump( $iterIter->current() ); // NULL
    var_dump( $iterIter->getInnerIterator()->current() ); // 1
    

    And also

    $iterIter->rewind();
    var_dump( $iterIter->current() ); // 1
    var_dump( $iterIter->getInnerIterator()->->current() );  // 1
    

    And also note that on an unitiliazed IteratorIterator:

    $iterIter->next(); // 2
    var_dump( $iterIter->current()) ; // 2 (from NULL to 2)
    var_dump( $iterIter->getInnerIterator()->current() );  // 2
    

    Note that $arrayIter from your code snippet is identical to $iterIter->getInnerIterator().

    Hope that shed some light.

提交回复
热议问题