Created
July 22, 2013 10:03
-
-
Save sorbing/6052745 to your computer and use it in GitHub Desktop.
PHP 5.5 Generators example, yield
This file contains 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 | |
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