foreach_003.phpt 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. --TEST--
  2. Iterator exceptions in foreach by value
  3. --FILE--
  4. <?php
  5. class IT implements Iterator {
  6. private $n = 0;
  7. private $count = 0;
  8. private $trap = null;
  9. function __construct($count, $trap = null) {
  10. $this->count = $count;
  11. $this->trap = $trap;
  12. }
  13. function trap($trap) {
  14. if ($trap === $this->trap) {
  15. throw new Exception($trap);
  16. }
  17. }
  18. function rewind(): void {$this->trap(__FUNCTION__); $this->n = 0;}
  19. function valid(): bool {$this->trap(__FUNCTION__); return $this->n < $this->count;}
  20. function key(): mixed {$this->trap(__FUNCTION__); return $this->n;}
  21. function current(): mixed {$this->trap(__FUNCTION__); return $this->n;}
  22. function next(): void {$this->trap(__FUNCTION__); $this->n++;}
  23. }
  24. foreach(['rewind', 'valid', 'key', 'current', 'next'] as $trap) {
  25. $obj = new IT(3, $trap);
  26. try {
  27. // IS_CV
  28. foreach ($obj as $key => $val) echo "$val\n";
  29. } catch (Exception $e) {
  30. echo $e->getMessage() . "\n";
  31. }
  32. unset($obj);
  33. try {
  34. // IS_VAR
  35. foreach (new IT(3, $trap) as $key => $val) echo "$val\n";
  36. } catch (Exception $e) {
  37. echo $e->getMessage() . "\n";
  38. }
  39. try {
  40. // IS_TMP_VAR
  41. foreach ((object)new IT(2, $trap) as $key => $val) echo "$val\n";
  42. } catch (Exception $e) {
  43. echo $e->getMessage() . "\n";
  44. }
  45. }
  46. ?>
  47. --EXPECT--
  48. rewind
  49. rewind
  50. rewind
  51. valid
  52. valid
  53. valid
  54. key
  55. key
  56. key
  57. current
  58. current
  59. current
  60. 0
  61. next
  62. 0
  63. next
  64. 0
  65. next