Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, what's the diff : $var2=$var1 ; $var2=&$var1; [duplicate]

Tags:

php

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 ?

like image 295
lovespring Avatar asked Aug 21 '10 10:08

lovespring


1 Answers

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.

like image 191
Colin Hebert Avatar answered Sep 24 '22 15:09

Colin Hebert