iterator_003.phpt 2.0 KB

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