5

Possible Duplicate:
Reference assignment operator in php =&

$var2 = $var1;
$var2 = &$var1;

Example:

$GLOBALS['a']=1;


function test()
{
    global $a;
    $local=2;
    $a=&$local;
}


test();

echo $a;

Why is $a still 1 ?

Community
  • 1
  • 1
lovespring
  • 19,051
  • 42
  • 103
  • 153

3 Answers3

13

The operator =& works with references and not values. The difference between $var2=$var1 and $var2=&$var1 is visible in this case :

$var1 = 1;
$var2 = $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 1'

$var1 = 1;
$var2 =& $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 2'

When you use the =& operator you don't say to $var2 "take the value of $var1 now" instead you say something like "Your value will be stored at the exact same place that the value of $var1". So anytime you change the content of $var1 or $var2, you will see the modification in the two variables.

For more informations look on PHP.net

EDIT : For the global part, you'll need to use $GLOBALS["a"] =& $local; Cf. documentation.

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • "If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the $GLOBALS array." Check the link i gave you, there is an entire section about globals. – Colin Hebert Aug 21 '10 at 12:40
5

When you do $var2 = $var1, PHP creates a copy of $var1, and places it in $var2. However, if you do $var2 = &$var1, no copy is made. Instead, PHP makes $var2 point at $var1 - what this means is that you end up with two variables that point at the exact same thing.

An example:

$var1 = "Foo";
$var2 = $var1; // NORMAL assignment - $var1's value is copied into $var2
$var3 = &$var1; // NOT normal copy!

echo $var2; // Prints "Foo".
echo $var3; // Also prints "Foo".

$var1 = "Bar"; // Change $var1.

echo $var2; // Prints "Foo" as before.
echo $var3; // Now prints "Bar"!
Stephen
  • 6,027
  • 4
  • 37
  • 55
  • wow, cloning the variable. neat. didn't know that. – DMin Aug 21 '10 at 11:04
  • "PHP makes $var2 point at $var1 - what this means is that you end up with two variables that point at the exact same thing." you're contradicting yourself; and only the second part is true. – Artefacto Aug 21 '10 at 17:09
1
global $a;

This is equivalent to:

$a = &$GLOBALS['a'];

When you assign $a a new reference, you're changing $a and not $GLOBALS['a'].

What do you expect to be output below?

$GLOBALS['a']=1;

function test()
{
    $a='foobar';          // $a is a normal variable
    $a=&$GLOBALS['a'];    // same as: global $a;
    $local=2;
    $a=&$local;
}

test();

echo $a;
strager
  • 88,763
  • 26
  • 134
  • 176