PHP RecursiveIteratorIterator:你能调用深度大于当前深度的getSubIterator()吗?

时间:2014-07-02 19:15:34

标签: php spl

当使用\RecursiveIteratorIterator的实例递归迭代时,在查找深度大于当前深度的子迭代器的预期行为时,它总是返回null

请参阅:RecursiveIteratorIterator::getSubIterator

  

public RecursiveIterator RecursiveIteratorIterator :: getSubIterator([   int $ level])

示例:

$innerIterator = new \RecursiveArrayIterator([/*a recursive array*/]);
$iterator = new \RecursiveIteratorIterator($innerIterator);

foreach ($iterator as $value) {
    $depth       = $iterator->getDepth();
    $parentDepth = $depth - 1;
    $childDepth  = $depth + 1;
    // returns \RecursiveArrayIterator
    $iterator->getSubIterator($depth);
    // returns null first iteration and \RecursiveArrayIterator thereafter
    $iterator->getSubIterator($parentDepth);
    // always returns null...should it?
    $iterator->getSubIterator($childDepth);
}

1 个答案:

答案 0 :(得分:3)

RecursiveIteratorIterator::getSubIterator()方法的源代码很短,可以在这里发布,并且可以找到答案。

/* {{{ proto RecursiveIterator RecursiveIteratorIterator::getSubIterator([int level])
   The current active sub iterator or the iterator at specified level */
SPL_METHOD(RecursiveIteratorIterator, getSubIterator)
{
    spl_recursive_it_object   *object = (spl_recursive_it_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
    long  level = object->level;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &level) == FAILURE) {
        return;
    }
    if (level < 0 || level > object->level) {
        RETURN_NULL();
    }
    RETURN_ZVAL(object->iterators[level].zobject, 1, 0);
} /* }}} */

- 来自PHP 5.5.14 source

这个问题的关键部分是if声明:

if (level < 0 || level > object->level) {
    RETURN_NULL();
}

代码非常明显,但是它说:

如果指定的级别小于零,或大于当前对象的级别,则返回 null