Jump to content

Archived

This topic is now archived and is closed to further replies.

atitthaker

difference between =& and =

Recommended Posts

Hej
 = is an assignment operator, a variable is assigned a value, =& is a reference operator, two variables reference one value.
 $varA = 1;
 $varA now has the value of 1

$varA =& $varB
 $varA now has the value of $varB, whatever that is.

Share this post


Link to post
Share on other sites
okay to expand on that, let's look at this example:

[code]$a = 'foo';
$b =& $a;

echo $a; // output: foo
echo $b; // output: foo
[/code]
okay at face value, it assigns the value of $a to $b. But what is really happening here is that you are assigning the reference pointer of $a to $b.  At this given point in time, they are both holding the value 'foo'. Now let's look expand this example:

[code]$a = 'foo';
$b =& $a;

echo $a; // output: foo
echo $b; // output: foo

$a = 'bar';

echo $a; // output: bar
echo $b; // output: bar

$b = 'foobar';

echo $a; // output: foobar
echo $b; // output: foobar
[/code]

same thing as before, at first.  but now when we assign 'bar' to $a, notice how echoing $a and $b both echo 'bar', instead of $b echoing 'foo'.  it is because the initial =& assigns the same memory location reference to both variables.  And again, if i were to go and assign 'foobar' to $b, you will see that they both now echo 'foobar'

both variables point to the same memory location.  changing one effectively changes the other, because the other one points to the same place, which you changed with the other. 

Share this post


Link to post
Share on other sites
BTW, Another common use for the & is for passing arguments to functions

In this first example, $foo is passed "by value" so the variable sent to the function is a copy of the original
[code]<?php
function f1 ($foo) {
    $foo *= 2;
    return $foo;
}

$foo = 3;
$bar = f1($foo);

echo $foo;        // 3
echo $bar;        // 6
?>
[/code]

In this example it is passed "by reference"  so a pointer to the original memory location is sent
[code]<?php
function f2 (&$foo) {
    $foo *= 2;
    return $foo;
}

$foo = 3;
$bar = f2($foo);

echo $foo;        // 6
echo $bar;        // 6
?>
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.