Bug #67633 [NEW]: A foreach on an array returned from a function not doing copy-on-write
| From: | tim at siliconengine dot com | Date: | Wed, 16 Jul 2014 15:11:58 +0000 |
| Subject: | Bug #67633 [NEW]: A foreach on an array returned from a function not doing copy-on-write | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-186671@lists.php.net to get a copy of this message | ||
From: tim at siliconengine dot com
Operating system: CentOS 6.5
PHP version: 5.5.14
Package: Arrays related
Bug Type: Bug
Bug description:A foreach on an array returned from a function not doing copy-on-write
Description:
------------
When passing an array by value to a function, which immediately returns
that array, and then using that return value in a foreach with a
reference, it allows modifying the original array as if it was passed by
reference.
These variants work properly:
............. Variant 1
[same main body]
function z($t)
{
// Force copy-on-write
$t[0] .= 'x';
return $t;
}
.............
............. Variant 2
$a = [ 'a', 'b', 'c' ];
$b = z($a);
// Assigning to variable causes proper copy-on-write behavior
foreach($b as &$x) {
$x .= 'q';
}
print_r($a);
[same z function]
.............
Test script:
---------------
<?php
$a = [ 'a', 'b', 'c' ];
foreach(z($a) as &$x) {
$x .= 'q';
}
print_r($a);
function z($t)
{
return $t;
}
Expected result:
----------------
Array
(
[0] => a
[1] => b
[2] => c
)
Actual result:
--------------
Array
(
[0] => aq
[1] => bq
[2] => cq
)
--
Edit bug report at https://bugs.php.net/bug.php?id=67633&edit=1
--