Skip to content

Instantly share code, notes, and snippets.

@sorbing
Created July 22, 2013 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorbing/6052745 to your computer and use it in GitHub Desktop.
Save sorbing/6052745 to your computer and use it in GitHub Desktop.
PHP 5.5 Generators example, yield
<?php
header("Content-type: text/plain");
function getLinesFromFile($file_path) {
// На каждой итерации выполняется код до первого yield
if ( ! $fh = fopen($file_path, 'r')) {
return;
}
$i = 1;
while (false !== $line = fgets($fh))
{
// yield возвращает все итерируемые элементы
yield str_pad($i++ . '.', 4, ' ') . $line;
}
// Если yield не будет вызван - выполнится эта часть ф-ции
fclose($fh);
}
// выполнения функции не происходит потому как внутри есть yield
$lines = getLinesFromFile(__FILE__);
foreach ($lines as $line) {
echo "$line";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment