Php SplFileObject中对fgets的第一次调用不';t高级文件密钥
考虑以下文本文件,Php SplFileObject中对fgets的第一次调用不';t高级文件密钥,php,iterator,spl,splfileobject,Php,Iterator,Spl,Splfileobject,考虑以下文本文件,test.txt: 1 2 3 以及以下PHP代码: <?php $file = new SplFileObject('test.txt', 'r'); var_dump($file->key()); $line = $file->fgets(); var_dump($file->key()); $line = $file->fgets(); var_dump($file->key()); $line = $file->fgets()
test.txt
:
1
2
3
以及以下PHP代码:
<?php
$file = new SplFileObject('test.txt', 'r');
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
$line = $file->fgets();
var_dump($file->key());
正如您所看到的,在第一次调用fgets()
之前和之后,key都是0。为什么?这是有意的吗?是虫子吗
行为是相同的设置SplFileObject::READ_AHEAD
标志
我使用的是PHP5.3.10-2
谢谢大家!
编辑
看,它认为这是一个错误
只返回行号:
293 /**
294 * @return line number
295 * @note fgetc() will increase the line number when reaing a new line char.
296 * This has the effect key() called on a read a new line will already
297 * return the increased line number.
298 * @note Line counting works as long as you only read the file and do not
299 * use fseek().
300 */
301 function key()
302 {
303 return $this->lnum;
304 }
存储在中,初始化为零:
26 private $lnum = 0;
当时,lnum
似乎没有发生任何变化,因此在创建之后,它仍然应该有一个0值:
32 /**
33 * Constructs a new file object
34 *
35 * @param $file_name The name of the stream to open
36 * @param $open_mode The file open mode
37 * @param $use_include_path Whether to search in include paths
38 * @param $context A stream context
39 * @throw RuntimeException If file cannot be opened (e.g. insufficient
40 * access rights).
41 */
42 function __construct($file_name, $open_mode = 'r', $use_include_path = false, $context = NULL)
43 {
44 $this->fp = fopen($file_name, $open_mode, $use_include_path, $context);
45 if (!$this->fp)
46 {
47 throw new RuntimeException("Cannot open file $file_name");
48 }
49 $this->fname = $file_name;
50 }
然后,应始终增加一个lnum
,包括第一次,而这不是它正在发生的情况:
60 /** increase current line number
61 * @return next line from stream
62 */
63 function fgets()
64 {
65 $this->freeLine();
66 $this->lnum++;
67 $buf = fgets($this->fp, $this->max_len);
68
69 return $buf;
70 }
只是将另一个变量设置为NULL
编辑2
我向PHP团队报告了一个bug:您应该发布源代码中的代码片段,fgets在其中调用
$this->lnum++
。我怀疑问题的根源可能更深,但你的观察似乎是正确的。
60 /** increase current line number
61 * @return next line from stream
62 */
63 function fgets()
64 {
65 $this->freeLine();
66 $this->lnum++;
67 $buf = fgets($this->fp, $this->max_len);
68
69 return $buf;
70 }