关于PHP迭代器的一道笔试题

我做事三分钟热度,却也爱你那么久。
### 问题
1
使对象可以像数组一样进行foreach循环,要求属性必须是私有。

鸟哥给出的答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class sample implements Iterator
{
private $_items = array(1,2,3,4,5,6,7);

public function __construct() {
;//void
}
public function rewind()
{
reset($this->_items);
}
public function current()
{
return current($this->_items);
}
public function key()
{
return key($this->_items);
}
public function next()
{
return next($this->_items);
}
public function valid()
{
return ( $this->current() !== false );
}
}

$sa = new sample();
foreach($sa as $key => $val){
print $key . "=>" .$val.'<br>';
}

拓展说明

使用foreach只可以循环出数组的public属性,protected和private属性无法得到

1
2
3
4
5
6
7
8
9
10
11
12
13
class User
{
public $a = 'tom';
protected $b = 'lilei';
private $c = 'hanmeimei';
public function __construct()
{
}
}

foreach (new User() as $user){
echo $user.'<br>';
}

但是在类的内部可以

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class User
{
public $a = 'tom';
protected $b = 'lilei';
private $c = 'hanmeimei';
public function do_something() {
foreach($this as $key => $value) {
echo "$key => $value\n";
}
}
}

$user = new User();
$user->do_something();

http://www.laruence.com/2008/10/31/574.html