/
17-iterator.php
89 lines (71 loc) · 1.54 KB
/
17-iterator.php
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
// === PHP has build-in Iterator interface ===
// That enforce iteration methods such as current(),
// next(), rewind(), valid() on given collection
class CarIterator implements Iterator
{
private $position = 0;
private $cars;
public function __construct(CarCollection $cars)
{
$this->cars = $cars;
}
public function current()
{
return $this->cars->getName($this->position);
}
public function key()
{
return $this->position;
}
public function next()
{
$this->position++;
}
public function rewind()
{
$this->position = 0;
}
public function valid()
{
return !is_null($this->cars->getName($this->position));
}
}
// === PHP has build-in IteratorAggregate interface ===
// That enforce getIterator() method to work
// in conjunction with Iterator interface
class CarCollection implements IteratorAggregate
{
private $names = [];
public function getIterator()
{
return new CarIterator($this);
}
public function setName($string)
{
$this->names[] = $string;
}
public function getName($key)
{
if (isset($this->names[$key])) {
return $this->names[$key];
}
return null;
}
public function is_empty()
{
return empty($this->$names);
}
}
// ---
$cars = new CarCollection();
$cars->setName('Fit');
$cars->setName('Vitz');
$cars->setName('Swift');
foreach($cars as $car){
echo $car . "\n";
}
// Output:
// Fit
// Vitz
// Swift