note 72301 deleted from language.references.whatdo by colder
| From: | colder@php.net | Date: | Sat, 24 Feb 2007 11:51:27 +0000 |
| Subject: | note 72301 deleted from language.references.whatdo by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-123830@lists.php.net to get a copy of this message | ||
Note Submitter: dkrysiak at o2 dot pl
----
I want to add an example for the following sentence from this page of manual:
"Note: If array with references is copied, its values are not dereferenced. This is valid also
for arrays passed by value to functions."
I ran into problems when using a code like this:
<?php
$a = 1;
$b = array(
'id' => 1,
'children' => & $a, // reference to $a
);
$c = $b; // copying and array - $a is copy of $b
$c['children'] = 2;
echo '<pre>$a = '; print_r($a); echo '</pre>';
echo '<pre>$b = '; print_r($b); echo '</pre>';
?>
This will output:
$a = 2
$b = Array
(
[id] => 1
[children] => 2
)
As is stated in cited note, when copying an array, it's elements are not dereferenced.
This mean that element, that was reference in original array, in the copy of the array is still the
reference to the original variable.
In my example changing $c['children'] changes also $b['children'] and even the
original variable: $a!
In $c, the 'children' elements stays a reference to $a as in the orignal table.
If you want to change 'children' only in $c, do the following:
<?php
unset($c['children']);
$c['children'] = 2;
?>
$a and $b['children'] will stay unchanged.
I hope this will help somebody :-)