Bug #67633 [Asn->Csd]: A foreach on an array returned from a function not doing copy-on-write
| From: | nikic@php.net | Date: | Sat, 20 Sep 2014 19:59:42 +0000 |
| Subject: | Bug #67633 [Asn->Csd]: A foreach on an array returned from a function not doing copy-on-write | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-187630@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=67633&edit=1
ID: 67633
Updated by: nikic@php.net
Reported by: tim at siliconengine dot com
Summary: A foreach on an array returned from a function not
doing copy-on-write
-Status: Assigned
+Status: Closed
Type: Bug
Package: Arrays related
Operating System: CentOS 6.5
PHP Version: 5.5.14
Assigned To: nikic
Block user comment: N
Private report: N
New Comment:
Automatic comment on behalf of nikic
Revision: http://git.php.net/?p=php-src.git;a=commit;h=5e977e69e144ca92868ae73cd3563eb473b75937
Log: Fixed bug #67633
Previous Comments:
------------------------------------------------------------------------
[2014-07-16 15:11:57] tim at siliconengine dot com
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 this bug report at https://bugs.php.net/bug.php?id=67633&edit=1