xref: /PHP-7.3/tests/lang/foreachLoop.010.phpt (revision 782352c5)
1--TEST--
2This test illustrates the impact of invoking destructors when refcount is decremented to 0 on foreach.
3It will pass only if the 'contentious code' in PHPValue.decReferences() is enabled.
4--FILE--
5<?php
6
7$a = array(1,2,3);
8$container = array(&$a);
9
10// From php.net:
11//   "Unless the array is referenced, foreach operates on a copy of
12//    the specified array and not the array itself."
13// At this point, the array $a is referenced.
14
15// The following line ensures $a is no longer references as a consequence
16// of running the 'destructor' on $container.
17$container = null;
18
19// At this point the array $a is no longer referenced, so foreach should operate on a copy of the array.
20// However, P8 does not invoke 'destructors' when refcount is decremented to 0.
21// Consequently, $a thinks it is still referenced, and foreach will operate on the array itself.
22// This provokes a difference in behaviour when changing the number of elements in the array while
23// iterating over it.
24
25$i=0;
26foreach ($a as $v) {
27	array_push($a, 'new');
28	var_dump($v);
29
30	if (++$i>10) {
31		echo "Infinite loop detected\n";
32		break;
33	}
34}
35
36?>
37--EXPECT--
38int(1)
39int(2)
40int(3)
41