请考虑以下文字文件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)
如您所见,在第一次拨打fgets()
之前和之后,密钥同样为0。为什么?有意吗?这是一个错误吗?
行为相同,设置SplFileObject::READ_AHEAD
标志。
我正在使用PHP 5.3.10-2
谢谢!
修改
查看SplFileObject
source code,它认为这是一个错误。
Method 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
instance variable中,初始化为零:
26 private $lnum = 0;
当creating a new instance时,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 }
然后,calls to 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
method只是将另一个变量设置为NULL。
修改2
我向PHP团队报告了一个错误:https://bugs.php.net/bug.php?id=61523