PHP 7 新增的生成器特性

本文和大家分享的主要是PHP 7  新增的生成器委托、生成器返回表达式等相关内容,一起来看看吧,希望对待 学习php7有所帮助。

生成器委托(Generator Delegation
  生成器委托(Generator Delegation )是  PHP 7  添加的特性,官方文档描述是:
  “In PHP 7, generator delegation allows you to yield values from another generator,  Traversable object, or  array by using the  yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.”
  生成器委托的形式为:  yield    的结果得是可遍历对象或数组。
  <?php declare(strict_types=1);
  $seh_seh_liām =  function () {
  $generator =  function () {
   yield from range(1, 3);
   foreach (range(4, 6)  as $i) {
   yield $i;
  }
  };
   foreach ($generator()  as $value) {
   echo " 每天念  PHP  是最好的编程语言  ... 第  $value  ...", PHP_EOL;
  }
  };
  $seh_seh_liām();
   生成器返回表达式(Generator Return Expression
  生成器返回表达式(Generator Return Expression )为生成器函数提供了增强内力,在  PHP 7  之前是无法在生成器函数内返回值的。
  举例如下:
  <?php
  $traverser = ( function () {
   yield "foo";
   yield "bar";
   return "value";
  })();
  $traverser->getReturn();  // Exception with message 'Cannot get return value of a generator that hasn't returned'
   foreach ($traverser  as $value) {
   echo "{$value}", PHP_EOL;
  }
  $traverser->getReturn();  // "value"
   生成器与Coroutine
  来个直接点的例子。
  <?php declare(strict_types=1);
   class  Coroutine{
   public  static  function  create(callable $callback) :  Generator
  {
   return ( function ()  use ($callback) {
   try {
   yield $callback;
  catch ( Exception $e) {
   echo "OH.. an error, but don't care and continue...", PHP_EOL;
  }
  })();
  }
   public  static  function  run(array $cos)
  {
  $cnt = count($cos);
   while ($cnt > 0) {
  $loc = random_int(0, $cnt-1);  //  用  random  模拟调度策略。
  $cos[$loc]->current()();
  array_splice($cos, $loc, 1);
  $cnt--;
  }
  }
  }
  $co =  new Coroutine();
  $cos = []; for ($i = 1; $i <= 10; $i++) {
  $cos[] = $co::create( function ()  use ($i) {  echo "Co.{$i}.", PHP_EOL; });
  }
  $co::run($cos);
  $cos = []; for ($i = 1; $i <= 20; $i++) {
  $cos[] = $co::create( function ()  use ($i) {  echo "Co.{$i}.", PHP_EOL; });
  }
  $co::run($cos);
来源:2gua

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值