Last active
March 12, 2020 23:44
-
-
Save ojhaujjwal/614c130096c9bb9d2a7d6e953ce20de2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FileIterator implements \Iterator { | |
protected $filePointer; | |
protected $data; | |
protected $key; | |
public function __construct($file) { | |
$this->filePointer = fopen($file, 'rb'); | |
if (!$this->filePointer) { | |
throw new \Exception('File could not be opened'); | |
}; | |
} | |
public function __destruct() { | |
fclose($this->filePointer); | |
} | |
public function current() { | |
return $this->data; | |
} | |
public function key() { | |
return $this->key; | |
} | |
public function next(): void { | |
$this->data = fgets($this->filePointer); | |
$this->key++; | |
} | |
public function rewind(): void { | |
fseek($this->filePointer, 0); | |
$this->data = fgets($this->filePointer); | |
$this->key = 0; | |
} | |
public function valid(): bool { | |
return false !== $this->data; | |
} | |
} | |
$lines = new FileIterator('/path-to-file'); | |
foreach ($lines as $line) { | |
echo $line. "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should the key be set to 0 in the constructor?