tags:

views:

240

answers:

2

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.

+1  A: 

There is nothing wrong here. The x in function set() is a local alias to the global variable x. In other words the global x and x in function set() point to the same value. After you do this:

$x =& $y[2];

Local x now points to the value of $y[2] but the global x still points to the old value. You need to read this page http://php.net/references

presario
+3  A: 

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: http://ca3.php.net/manual/en/language.references.arent.php

You may want to declare set() to return a reference:

function &set(&$x, &$y) {}

And call it like this:

$x =& set($x,$y);

See http://ca3.php.net/manual/en/language.references.return.php

zombat