I am trying to set a reference in a function. But, I am not able to get this working.
Code I tried:
function set(&$x, &$y)
{
$x =& $y[2];
}
$y = array(
0,
1,
array('something')
);
$x = array('old_val');
print "1. inited, x is:\n";
print_r($x);
set($x, $y);
print "\n2. now, x is: ";
print_r($x);
Output:
1. inited, x is:
Array
(
[0] => old_val
)
2. now, x is: Array
(
[0] => old_val
)
I am expecting the value of $x to be same as $y[2]. Also, any further modification to $x should change $y[2]. (As in pointer assignment in C: x = &y[2]; )
What am I doing wrong? Any suggestions appreciated.
Edit:
actually, the function set() in the test code is a simplified one for my testing purpose. It is actually select_node(&$x, &$tree, $selector) : This will select a node from the tree which matches $selector and assigns it to $x.
References aren’t pointers, and act slightly differently.
What’s happening is that the $x variable inside the set() function is being bound to the same location as $y[2], but $x inside set() is not the same as $x outside of set(). They both point to the same location, but you have only updated the one inside of set(), which is no longer relevant once set() returns. There is no way to bind the $x in the calling scope, as it does not exist inside the function.
See: https://www.php.net/manual/en/language.references.arent.php
You may want to declare set() to return a reference:
And call it like this:
See https://www.php.net/manual/en/language.references.return.php