1--TEST-- 2Foreach loop tests - substituting the entire iterated entity during the loop. 3--FILE-- 4<?php 5 6class C { 7 public $a = "Original a"; 8 public $b = "Original b"; 9 public $c = "Original c"; 10 public $d = "Original d"; 11 public $e = "Original e"; 12} 13 14echo "\nSubstituting the iterated object for a different object.\n"; 15$obj = new C; 16$obj2 = new stdclass; 17$obj2->a = "new a"; 18$obj2->b = "new b"; 19$obj2->c = "new c"; 20$obj2->d = "new d"; 21$obj2->e = "new e"; 22$obj2->f = "new f"; 23$ref = &$obj; 24$count=0; 25foreach ($obj as $v) { 26 var_dump($v); 27 if ($v==$obj->b) { 28 $ref=$obj2; 29 } 30 if (++$count>10) { 31 echo "Loop detected.\n"; 32 break; 33 } 34} 35var_dump($obj); 36 37echo "\nSubstituting the iterated object for an array.\n"; 38$obj = new C; 39$a = array(1,2,3,4,5,6,7,8); 40$ref = &$obj; 41$count=0; 42foreach ($obj as $v) { 43 var_dump($v); 44 if ($v==="Original b") { 45 $ref=$a; 46 } 47 if (++$count>10) { 48 echo "Loop detected.\n"; 49 break; 50 } 51} 52var_dump($obj); 53 54echo "\nSubstituting the iterated array for an object.\n"; 55$a = array(1,2,3,4,5,6,7,8); 56$obj = new C; 57$ref = &$a; 58$count=0; 59foreach ($a as $v) { 60 var_dump($v); 61 if ($v===2) { 62 $ref=$obj; 63 } 64 if (++$count>10) { 65 echo "Loop detected.\n"; 66 break; 67 } 68} 69var_dump($obj); 70 71?> 72--EXPECTF-- 73 74Substituting the iterated object for a different object. 75string(10) "Original a" 76string(10) "Original b" 77string(5) "new a" 78string(5) "new b" 79string(5) "new c" 80string(5) "new d" 81string(5) "new e" 82string(5) "new f" 83object(stdClass)#%d (6) { 84 ["a"]=> 85 string(5) "new a" 86 ["b"]=> 87 string(5) "new b" 88 ["c"]=> 89 string(5) "new c" 90 ["d"]=> 91 string(5) "new d" 92 ["e"]=> 93 string(5) "new e" 94 ["f"]=> 95 string(5) "new f" 96} 97 98Substituting the iterated object for an array. 99string(10) "Original a" 100string(10) "Original b" 101int(1) 102int(2) 103int(3) 104int(4) 105int(5) 106int(6) 107int(7) 108int(8) 109array(8) { 110 [0]=> 111 int(1) 112 [1]=> 113 int(2) 114 [2]=> 115 int(3) 116 [3]=> 117 int(4) 118 [4]=> 119 int(5) 120 [5]=> 121 int(6) 122 [6]=> 123 int(7) 124 [7]=> 125 int(8) 126} 127 128Substituting the iterated array for an object. 129int(1) 130int(2) 131string(10) "Original a" 132string(10) "Original b" 133string(10) "Original c" 134string(10) "Original d" 135string(10) "Original e" 136object(C)#%d (5) { 137 ["a"]=> 138 string(10) "Original a" 139 ["b"]=> 140 string(10) "Original b" 141 ["c"]=> 142 string(10) "Original c" 143 ["d"]=> 144 string(10) "Original d" 145 ["e"]=> 146 string(10) "Original e" 147} 148