考虑以下文本文件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());
它输出:
int(0) int(0) int(1) int(2) int(3)
如您所见, key 在第一次调用之前和之后都为 0 fgets()
。为什么?是有意的吗?它是一个错误吗?
行为是相同的设置SplFileObject::READ_AHEAD
标志。
我在用着PHP 5.3.10-2
谢谢!
编辑
查看SplFileObject
源代码,它认为这是一个错误。
方法key()
只返回行号:
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 }
它存储在lnum
实例变量中,初始化为零:
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 }
然后,调用fgets
应该总是增加一个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 }
freeline
方法只是将另一个变量设置为 NULL。
编辑 2
我向 PHP 团队报告了一个错误:https ://bugs.php.net/bug.php?id=61523