https://www.jianshu.com/p/86fefb0aacd9
http://www.laruence.com/2015/05/28/3038.html
yield
让出,返回的意思,返回一个生成器对象,可以被遍历,每次他都返回yield右侧的值并中断在那里
如果你调用生成器的current()方法,将获取到当前值,如果调用send()方法,将改变当前值,并执行到下一个yield后停下来,如果yeild在等号右侧,send()会先改变当前值,然后赋值,如下所示
也就是说,yield的current send方法获取到的总是当前的值,而yield左侧的值如果有send就是是send过去的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function gen() { $ret = (yield 'yield1'); var_dump($ret); $ret = (yield 'yield2'); var_dump($ret); } $gen = gen(); var_dump($gen->current()); var_dump($gen->send('ret1')); var_dump($gen->send('ret2'));
function gen() { yield 'foo'; yield 'bar'; } $gen = gen(); var_dump($gen->current()); var_dump($gen->send('something')); var_dump($gen->next()); var_dump($gen->current());
|
yield通信
1 2 3 4 5 6 7 8 9 10 11
| function logger($fileName) { $fileHandle = fopen($fileName, 'a'); while (true) { fwrite($fileHandle, yield . "\n"); } } $logger = logger(__DIR__ . '/log'); $logger->send('Foo'); $logger->send('Bar');
|
处理大数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
$t1 = microtime(true); class common_data { public function data() { $array = []; for ($i = 1; $i <= 1000000; $i++) { $array[] = 'item_' . $i; } return $array; } public function callback($param) { return $param; } } $commn = new common_data(); $data = $commn->data(); foreach ($data as $value) { $commn->callback($value); } $t2 = microtime(true); echo '耗时' . round($t2 - $t1, 7) . '秒' . PHP_EOL; echo '内存: ' . memory_get_usage() / 1024 . 'K' . PHP_EOL;
$t1 = microtime(true); class yield_data { public function data() { for ($i = 1; $i <= 1000000; $i++) { $array = 'item_' . $i; yield $array; } } public function callback($param) { return $param; } } $yield = new yield_data(); $data = $yield->data(); foreach ($data as $value) { $yield->callback($value); } $t2 = microtime(true); echo '耗时' . round($t2 - $t1, 7) . '秒' . PHP_EOL; echo '内存: ' . memory_get_usage() / 1024 . 'K' . PHP_EOL;
|
Generator
1 2 3 4 5 6 7 8 9 10 11
| Generator implements Iterator { public mixed current ( void ) public mixed key ( void ) public void next ( void ) public void rewind ( void ) public mixed send ( mixed $value ) public void throw ( Exception $exception ) public bool valid ( void ) public void __wakeup ( void ) public mixed getReturn ( void ) }
|