foreach_004.phpt 1.3 KB

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