Skip to content

Instantly share code, notes, and snippets.

@hirak
Last active August 29, 2015 14:02
Show Gist options
  • Save hirak/229060655e951a6288f3 to your computer and use it in GitHub Desktop.
Save hirak/229060655e951a6288f3 to your computer and use it in GitHub Desktop.
Iteratorをimplementsする奴は情弱。IteratorAggregateを使え ref: http://qiita.com/Hiraku/items/14722922441f9ed3fbbb
<?php
class A {
public $hoge = 1;
public $fuga = 2;
private $pri = 3;
protected $pro = 4;
}
$a = new A;
foreach ($a as $key => $val) {
var_dump($key, $val);
}
string(4) "hoge"
int(1)
string(4) "fuga"
int(2)
interface Iterator extends Traversable
{
function current();
function key();
function next();
function rewind();
function valid();
}
//冒頭のFabienさんの記事から丸ごと引用
class Foo implements Iterator
{
protected $attributes = array();
function __construct(array $arr)
{
$this->attributes = $arr;
}
function rewind()
{
reset($this->attributes);
}
function current()
{
return current($this->attributes);
}
function key()
{
return key($this->attributes);
}
function next()
{
return next($this->attributes);
}
function valid()
{
return false !== current($this->attributes);
}
}
interface IteratorAggregate extends Traversable
{
function getIterator();
}
class Foo implements IteratorAggregate
{
protected $attributes = array();
function __construct(array $arr)
{
$this->attributes = $arr;
}
function getIterator()
{
return new ArrayIterator($this->attributes);
}
}
class Foo implements IteratorAggregate
{
protected $attributes = array();
function __construct(array $arr)
{
$this->attributes = $arr;
}
function getIterator()
{
foreach ($this->attributes as $key => $val) {
yield $key => $val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment