Jump to content

difference between =& and =


atitthaker

Recommended Posts

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. 
Link to comment
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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.