Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active June 10, 2016 10:01
Show Gist options
  • Save sword-jin/806634ab52412622b7d499f79c4c4d57 to your computer and use it in GitHub Desktop.
Save sword-jin/806634ab52412622b7d499f79c4c4d57 to your computer and use it in GitHub Desktop.
Generator
<?php
// basic
function _genetator () {
yield "one";
yield "two";
yield "three";
}
foreach (_genetator() as $value) {
echo $value, PHP_EOL;
}
/*
one
two
three
*/
// Assign a int size instead of a big size area.
function _range ($length) {
for ($i = 0; $i < $length; $i ++) {
yield $i;
}
}
foreach (_range(10000000) as $value) {
echo $value, PHP_EOL;
}
/*
0
1
...
*/
// generator key-value
$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;
function input_parser($input) {
foreach (explode("\n", $input) as $line) {
$fields = explode(';', $line);
$id = array_shift($fields);
yield $id => $fields;
}
}
foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
// read file
function readFileLine($file) {
$handle = fopen($file, 'r');
if (! $handle) {
throw new Exception("Can't read this file");
}
while (($line = fgets($handle)) !== false) {
yield $line;
}
if (! feof($handle)) {
throw new Exception("Error: unecxepted fgets() fails");
}
fclose($handle);
}
// send to yield
function loger () {
while (true) {
$string = yield;
echo $string, PHP_EOL;
}
}
$loger = loger();
$loger->send('one');
$loger->send('two');
$loger->send('three');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment