为 class php 配置自己的迭代器?
configure own iterator for class php?
我有一个 class 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;
}
}
我们能做到吗?怎么样?
您需要实现 Iterator 接口。
class Foo implements Iterator {
您应该查看内置接口:
您需要实现 \Iterator or \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;
}
我有一个 class 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;
}
}
我们能做到吗?怎么样?
您需要实现 Iterator 接口。
class Foo implements Iterator {
您应该查看内置接口:
您需要实现 \Iterator or \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;
}