在每次函数调用时依次返回数组中的项,当不存在时返回false


Return items from array sequentially on each function call, false when no more exist

我需要有一个函数,有点像mysql资源有时做的,你必须"获取"的东西作为循环的一部分,直到它返回false。

我有这样的东西:

while ($variable = $object->method())
{
  // Do stuff with variable here
}

我正在尝试找出如何在我的对象上最好地跟踪从方法发送的内容。

class object {
  $values = array(1, 2);
  public function method()
    {
      // First call should return 1, second should return 2, and any subsequent calls should return FALSE
      // Not sure now what to do
      // return $values[$i];
    }
}

使用each()函数。它移动数组的内部指针并返回当前值。如果没有其他值,则返回false。

return each($values);

还具有不具有破坏性的优点

您可以简单地使用return array_shift($values)。(文档)。

你也可以通过foreach实现Iterator或IteratorAggregate接口,使你的对象"可遍历",例如:

<?php
class object implements IteratorAggregate {
  protected $values;
  public function __construct() {
    $this->values = range(1,10);
  }
  public function getIterator() {
    return new ArrayIterator($this->values);
  }
}
$o = new object;
foreach( $o as $e ) {
    echo $e;
}

打印12345678910