1

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
  • Okay, very weird. It works if you assign something to $x within the function (it puts it back into the array and it is set outside of the function), but it doesn't work the other way around...hmmm. Commented Mar 25, 2009 at 5:51

2 Answers 2

3

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:

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

And call it like this:

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

See https://www.php.net/manual/en/language.references.return.php

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.