我有一个Foo课,我需要这样做:
$foo = new Foo();
foreach($foo as $value)
{
echo $value;
}
并定义我自己的方法来迭代这个对象,例如:
class Foo
{
private $bar = [1, 2, 3];
private $baz = [4, 5, 6];
function create_iterator()
{
//callback to the first creation of iterator for this object
$this->do_something_one_time();
}
function iterate()
{
//callback for each iteration in foreach
return $this->bar + $this->baz;
}
}
我们可以这样做吗?怎么样?
答案 0 :(得分:1)
答案 1 :(得分:1)
您需要实现\Iterator或\IteratorAggregate界面才能实现这一目标。
使用\ IteratorAggregate和\ Iterator接口尝试实现的一个简单示例(我省略了\ Iterator实现细节,但您可以使用PHP文档查看它们的工作方式):
class FooIterator implements \Iterator
{
private $source = [];
public function __construct(array $source)
{
$this->source = $source;
// Do whatever else you need
}
public function current() { ... }
public function key() { ... }
public function next()
{
// This function is invoked on each step of the iteration
}
public function rewind() { ... }
public function valid() { ... }
}
class Foo implements \IteratorAggregate
{
private $bar = [1, 2, 3];
private $baz = [4, 5, 6];
public function getIterator()
{
return new FooIterator(array_merge($this->bar, $this->baz));
}
}
$foo = new Foo();
foreach ($foo as $value) {
echo $value;
}