xref: /PHP-7.0/ext/spl/tests/iterator_003.phpt (revision 610c7fbe)
1--TEST--
2SPL: CachingIterator and __toString()
3--FILE--
4<?php
5
6class Student
7{
8	private $id;
9	private $name;
10
11    public function __construct($id, $name)
12    {
13    	$this->id = $id;
14    	$this->name = $name;
15    }
16
17	public function __toString()
18	{
19		return $this->id . ', ' . $this->name;
20	}
21
22	public function getId()
23	{
24		return $this->id;
25	}
26}
27
28class StudentIdFilter extends FilterIterator
29{
30	private $id;
31
32	public function __construct(ArrayObject $students, Student $other)
33	{
34		FilterIterator::__construct($students->getIterator());
35		$this->id = $other->getId();
36	}
37
38	public function accept()
39	{
40		echo "ACCEPT ".$this->current()->getId()." == ".$this->id."\n";
41		return $this->current()->getId() == $this->id;
42	}
43}
44
45class StudentList implements IteratorAggregate
46{
47	private $students;
48
49	public function __construct()
50	{
51		$this->students = new ArrayObject(array());
52	}
53
54	public function add(Student $student)
55	{
56		if (!$this->contains($student)) {
57			$this->students[] = $student;
58		}
59	}
60
61	public function contains(Student $student)
62	{
63		foreach ($this->students as $s)
64		{
65			if ($s->getId() == $student->getId()) {
66				return true;
67			}
68		}
69		return false;
70	}
71
72	public function getIterator() {
73		return new CachingIterator($this->students->getIterator(), true);
74	}
75}
76
77$students = new StudentList();
78$students->add(new Student('01234123', 'Joe'));
79$students->add(new Student('00000014', 'Bob'));
80$students->add(new Student('00000014', 'Foo'));
81
82// The goal is to verify we can access the cached string value even if it was
83// generated by a call to __toString(). To check this we need to access the
84// iterator's __toString() method.
85$it = $students->getIterator();
86foreach ($it as $student) {
87	echo $it->__toString(), "\n";
88}
89?>
90===DONE===
91<?php exit(0); ?>
92--EXPECT--
9301234123, Joe
9400000014, Bob
95===DONE===
96