在每个函数调用时按顺序返回数组中的项,如果不存在则返回false

时间:2011-12-03 22:25:50

标签: php

我需要有一个类似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];
    }
}

3 个答案:

答案 0 :(得分:2)

使用each()功能。它移动数组的内部指针并返回当前值。如果不存在更多值,则返回false。

return each($values);

它还具有不具破坏性的优势。

答案 1 :(得分:0)

您可以在案件中return array_shift($values)。 (docs)。

答案 2 :(得分:0)

您也可以通过实施IteratorIteratorAggregate界面,通过foreach使您的对象“可遍历”,例如:

<?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