SPLFileObject next() 行为
在 PHP 中,SPLFileObject 允许将文件视为迭代器。
然而有一种行为我不理解。当您在对象上调用 next() 时,它会增加 key() 的值,但不会前进文件中的行,除非您在每次迭代时调用 current() 。 SPL 文档指出 key() 返回当前行号。
要重现的代码:
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
谁能解释一下这是一个错误还是预期的行为?
查看了 google 和 php 论坛,但没有任何结果。提前致谢。
In PHP SPLFileObject allows treating files as iterators.
Yet there is a behavior that I don't understand. When you call next() on the object it increments the value of key() but does not advance the line in the file unless you call current() with each iteration. The SPL docs state that key() returns current line number.
Code to reproduce:
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
From what i can see, the next is not working on this section. It will advance if i use it this way:
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
Could anyone explain if this is a bug or if it is intended behavior?
Looked over google and php forums and nothing came up. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SPLFileObject::next() 仅在 READ_AHEAD 时有效标志已设置。
SPLFileObject::next() only has an effect if the READ_AHEAD flag has been set.
好吧,无论如何,为什么不将它与 foreach 一起使用,因为这就是它的用途呢?
Well, in any case, why don't you use it with foreach, as it's what it's intended for?