|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2002-12-13 12:00 UTC] henrik dot gebauer at web dot de
I create an array an then a reference to an element of that array.
Then the array is passed to a function (by value!) which changes the value of the element.
After that, the global array has also another value.
I would expect this behaviour if I passed the array by reference but I did not.
<?php
$array = array(1);
$reference =& $array[0];
echo $array[0], '<br>';
theFunction($array);
echo $array[0], '<br>';
function theFunction($array) {
$array[0] = 2;
}
?>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 04:00:01 2025 UTC |
This is my best effort (with the help of a friend), to document this issue. I have based it on my personal tests as well as information from this and related bug reports, but I assume it goes without saying that this patch should be reviewed by a developer with knowledge in this area before being committed. Thanks for a great programing language! Index: references.xml =================================================================== RCS file: /repository/phpdoc/en/language/references.xml,v retrieving revision 1.27 diff -u -r1.27 references.xml --- references.xml 2003/12/21 15:37:29 1.27 +++ references.xml 2004/04/21 19:20:39 @@ -43,6 +43,21 @@ </para> </note> </para> + <warning> + <simpara> + Due to peculiarities of the internal workings of PHP, if a reference + is made to a single element of an array and then the array is copied, + whether by assignment or when passed by value in a function call, + the reference is copied as part of the array. This means that + changes to any such elements in either array will be duplicated in + the other array (and in the other references), even if the arrays + have different scopes (e.g. one is an argument inside a function and + the other is global)! Elements that did not have references at the + time of the copy, as well as references assigned to those other + elements after the copy of the array, will behave normally (i.e. + independent of the other array). + </simpara> + </warning> <para> The same syntax can be used with functions, that return references, and with <literal>new</literal> operator (in PHP 4.0.4 and later):