array_005.phpt 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. --TEST--
  2. SPL: ArrayObject/Iterator interaction
  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 $this->students->getIterator();
  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. foreach ($students as $student) {
  69. echo $student, "\n";
  70. }
  71. ?>
  72. --EXPECT--
  73. 01234123, Joe
  74. 00000014, Bob