File: foreachLoop.010.phpt

package info (click to toggle)
php8.4 8.4.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 211,276 kB
  • sloc: ansic: 1,176,142; php: 35,419; sh: 11,964; cpp: 7,208; pascal: 4,951; javascript: 3,091; asm: 2,817; yacc: 2,411; makefile: 696; xml: 446; python: 301; awk: 148
file content (40 lines) | stat: -rw-r--r-- 1,178 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
--TEST--
This test illustrates the impact of invoking destructors when refcount is decremented to 0 on foreach.
It will pass only if the 'contentious code' in PHPValue.decReferences() is enabled.
--FILE--
<?php

$a = array(1,2,3);
$container = array(&$a);

// From php.net:
//   "Unless the array is referenced, foreach operates on a copy of
//    the specified array and not the array itself."
// At this point, the array $a is referenced.

// The following line ensures $a is no longer references as a consequence
// of running the 'destructor' on $container.
$container = null;

// At this point the array $a is no longer referenced, so foreach should operate on a copy of the array.
// However, P8 does not invoke 'destructors' when refcount is decremented to 0.
// Consequently, $a thinks it is still referenced, and foreach will operate on the array itself.
// This provokes a difference in behaviour when changing the number of elements in the array while
// iterating over it.

$i=0;
foreach ($a as $v) {
    array_push($a, 'new');
    var_dump($v);

    if (++$i>10) {
        echo "Infinite loop detected\n";
        break;
    }
}

?>
--EXPECT--
int(1)
int(2)
int(3)