如何解决访问 Iterator 接口的 PHP 代码有哪些等价于 foreach 循环?
假设我们有一个 Iteraror
。什么代码相当于 foreach
ing it?
function foreach_(Iterator $i): void
{
foreach ($i as $k => $v) {
}
}
解决方法
下面的代码是等价的:
function for_(Iterator $i): void
{
for ($i->rewind(); $i->valid(); $i->next()) {
$i->current();
$i->key();
}
}
这是我的测试方式:
class IteratorTest extends TestCase
{
/**
* @dataProvider provide
*/
public function testDoesTheSameWithIterator(
Iterator $i,callable $expectedFn,callable $actualFn
): void {
$expectedI = new Iterator_($i);
$actualI = new Iterator_($i);
$expectedFn($expectedI);
$actualFn($actualI);
var_export($expectedI->calls);
self::assertSame($expectedI->calls,$actualI->calls);
}
public function provide(): array
{
return [
'for iterator vs foreach' => [
new ArrayIterator(['a' => 1,2 => 'b',3 => null]),__NAMESPACE__ . '\foreach_',__NAMESPACE__ . '\for_',],];
}
}
class Iterator_ implements Iterator
{
public array $calls = [];
private Iterator $i;
public function __construct(Iterator $i)
{
$this->i = $i;
}
public function __call($method,$arguments)
{
$return = $this->i->$method(...$arguments);
$this->calls[] = compact('method','arguments','return');
return $return;
}
public function current()
{
return $this->__call(__FUNCTION__,func_get_args());
}
public function next(): void
{
$this->__call(__FUNCTION__,func_get_args());
}
public function key()
{
return $this->__call(__FUNCTION__,func_get_args());
}
public function valid(): bool
{
return $this->__call(__FUNCTION__,func_get_args());
}
public function rewind(): void
{
$this->__call(__FUNCTION__,func_get_args());
}
}
测试结果如下:
array (
0 =>
array (
'method' => 'rewind','arguments' =>
array (
),'return' => NULL,),1 =>
array (
'method' => 'valid','return' => true,2 =>
array (
'method' => 'current','return' => 1,3 =>
array (
'method' => 'key','return' => 'a',4 =>
array (
'method' => 'next',5 =>
array (
'method' => 'valid',6 =>
array (
'method' => 'current','return' => 'b',7 =>
array (
'method' => 'key','return' => 2,8 =>
array (
'method' => 'next',9 =>
array (
'method' => 'valid',10 =>
array (
'method' => 'current',11 =>
array (
'method' => 'key','return' => 3,12 =>
array (
'method' => 'next',13 =>
array (
'method' => 'valid','return' => false,)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。