Bug #80826 [Opn->Nab]: Array member reference affecting pass by value assignment
Edit report at https://bugs.php.net/bug.php?id=80826&edit=1
ID: 80826
Updated by: requinix@php.net
Reported by: tshumbeo at mailhouse dot biz
Summary: Array member reference affecting pass by value
assignment
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Windows & Linux
PHP Version: 7.4.15
Block user comment: N
Private report: N
New Comment:
There is a big red note in foreach's documentation about this.
Previous Comments:
------------------------------------------------------------------------
[2021-03-03 19:46:30] tshumbeo at mailhouse dot biz
Description:
------------
See the test script. When (1) is not present (leaving the member reference in the outside scope when
f() is called), the assignment inside f() is able to modify the passed array even though it
doesn't accept it by reference (note "&array(1)" in Actual Result). Removing the
reference explicitly with (1) avoids this problem.
Test script:
---------------
<?php
$a = [1, 2, 3];
foreach ($a as &$reference) {
$reference = (object) ['x' => $reference];
}
// (1)
//unset($reference);
f($a);
var_dump($a);
function f($a) {
foreach ($a as $k => $v) {
$a[$k] = [$v];
}
}
Expected result:
----------------
array(3) {
[0]=>
object(stdClass)#1 (1) {
["x"]=>
int(1)
}
[1]=>
object(stdClass)#2 (1) {
["x"]=>
int(2)
}
[2]=>
object(stdClass)#3 (1) {
["x"]=>
int(3)
}
}
Actual result:
--------------
array(3) {
[0]=>
object(stdClass)#1 (1) {
["x"]=>
int(1)
}
[1]=>
object(stdClass)#2 (1) {
["x"]=>
int(2)
}
[2]=>
&array(1) { // !!!
[0]=>
object(stdClass)#3 (1) {
["x"]=>
int(3)
}
}
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=80826&edit=1
Thread (7 messages)