Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

SplFileObject::fgets() No Longer Caches The Current Line

SplFileObject::fgets() used to cache the line it read so that a following current() call returned that same cached line instead of reading again. It also let next() be called past end-of-file an unlimited number of times, incrementing key() without bound. In PHP 8.6, fgets() no longer caches the line for current(), so current() now reads and returns the next line from the stream; next() past EOF is now a no-op, so key() stops advancing once the end of the file is reached.

PHP code

<?php

$path = tempnam(sys_get_temp_dir(), 'spl');
file_put_contents($path, "line1\nline2\nline3\n");

$f = new SplFileObject($path);
var_dump(trim($f->fgets()));
var_dump(trim($f->current()));

for ($i = 0; $i < 5; $i++) {
    $f->next();
}
var_dump($f->key());

unlink($path);

?>

Before

string(5) line1
string(5) line1
int(5)

After

string(5) line1
string(5) line2
int(3)

PHP version change

This behavior changed in 8.6.

See Also

Extension

© 2023-2026, Damien Seguy - Exakat