i thought, that i understand what references do. but now i meet an example, which can't understand anyway.
i saw an interesting script here, but why he use &
in this script i can't understand. here is the part of script
foreach ($nodeList as $nodeId => &$node)
{
if (!$node['id_parrent'] || !array_key_exists($node['id_parrent'], $nodeList))
{
$tree[] = &$node;
}
else
{
$nodeList[$node['id_parrent']]['children'][] =&$node;
}
}
if he doesn't make any changes on $node, why it is needed to use references here? there is nothing like $node = any changes
, so why use =& $node, instead $node?
maybe you will help me to understand?
Thanks
$tree[] = &$node;
When you do it like this, the tree array will store references to the same nodes as in the node list. If you change a node from the node list, it will be changed in the tree too and vice-versa of course. The same applies to the children array.
Without using references, the tree and children array would simply contain a copy of the node.
if he doesn't make any changes on $node, why it is needed to use references here? there is nothing like $node = any changes, so why use =& $node, instead $node?
Because using a reference also saves you from copying the variable, thus saving memory and (in a usually negligeable dimension) performance.
I would suggest you to have a look at:
PHP: Pass by reference vs. Pass by value
This easily demonstrates why you need to pass variables by reference (&
).
Example code taken:
function pass_by_value($param) {
push_array($param, 4, 5);
}
$ar = array(1,2,3);
pass_by_value($ar);
foreach ($ar as $elem) {
print "<br>$elem";
}
The code above prints 1, 2, 3. This is because the array is passed as value.
function pass_by_reference(&$param) {
push_array($param, 4, 5);
}
$ar = array(1,2,3);
pass_by_reference($ar);
foreach ($ar as $elem) {
print "<br>$elem";
}
The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that the function (pass_by_reference) doesn't manipulate a copy of the variable passed, but the actual variable itself.