2014-10-29 103 views
1

我试图运行下面的代码,并得到一个错误“)提供的foreach(无效参数”:的foreach():无效的参数传递

<?php 
function xrange($start, $limit, $step = 1) { 
    if ($start < $limit) { 
     if ($step <= 0) { 
      throw new LogicException('Step must be +ve'); 
     } 

     for ($i = $start; $i <= $limit; $i += $step) { 
      yield $i; 
     } 
    } else { 
     if ($step >= 0) { 
      throw new LogicException('Step must be -ve'); 
     } 

     for ($i = $start; $i >= $limit; $i += $step) { 
      yield $i; 
     } 
    } 
} 

/* 
* Note that both range() and xrange() result in the same 
* output below. 
*/ 

echo 'Single digit odd numbers from range(): '; 
foreach (range(1, 9, 2) as $number) { 
    echo "$number "; 
} 
echo "\n"; 

echo 'Single digit odd numbers from xrange(): '; 
foreach (xrange(1, 9, 2) as $number) { 
    echo "$number "; 
} 
?> 

任何人都可以提出什么样的根本原因是作为即时通讯无法找出?

+1

你有什么PHP版本? 'yield'是针对php 5.5及以上版本的。 – Cheery 2014-10-29 07:53:23

+0

@Gunaseelan这只是手册中的一个例子。 http://php.net/manual/en/language.generators.overview.php – Cheery 2014-10-29 07:57:15

+0

@Cheery:它对我来说是5.4,如果是这样的话,我可以使用什么来代替yield来运行这个代码与我当前的PHP建立? – 2014-10-29 07:57:43

回答

-1

yield关键字只能用于5.5版本以后的PHP。或者,你可以修改你的功能:

function xrange($start, $limit, $step = 1) { 
    $num = array(); 
    if ($start < $limit) { 
     if ($step <= 0) { 
      throw new LogicException('Step must be +ve'); 
     } 

     for ($i = $start; $i <= $limit; $i += $step) { 
      $num[]= $i; 
     } 
    } else { 
     if ($step >= 0) { 
      throw new LogicException('Step must be -ve'); 
     } 

     for ($i = $start; $i >= $limit; $i += $step) { 
      $num[]= $i; 
     } 
    } 
    return $num; 
} 

,这将工作得很好。

+0

谢谢。有效。 – 2014-10-29 08:03:12