在PHP SPLFileObject允许治疗文件作为迭代器。

然而,有是我不理解的行为。当你调用next()对象上它递增键的值(),但除非你叫电流()在每次迭代不前进行的文件中。的SPL文档指出键()返回当前行号。

代码重现:

的test.txt

0
1
2
3

iterator.php

<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n"; // prints 0
echo $fi->key() . "\n"; //prints 0
$fi->next();
$fi->next();
$fi->next();
echo $fi->current() . "\n"; // prints 1, expecting 3
echo $fi->key() . "\n"; //prints 3

从我所看到的,接下来是不工作的这一部分。就会提前如果我使用这种方式:

iterator_fix.php

<?php
$fi = new SPLFileObject('test.txt');
echo $fi->current() . "\n"; // prints 0
echo $fi->key() . "\n"; //prints 0
$fi->next();
$fi->current();
$fi->next();
$fi->current();
$fi->next();
echo $fi->current() . "\n"; // prints 3 as expected
echo $fi->key() . "\n"; //prints 3

任何人都可以解释,如果这是一个错误,或者如果它是预期的行为?

看着谷歌和PHP论坛,一无所获。由于事先。

其他提示

那么,在任何情况下,你为什么不使用的foreach使用它,因为它就是它的打算?

scroll top