0

I've been looking everywhere for a satisfactory answer to this. Still not wrapping my head around the usefulness of the & character when used as a reference. Why would I want to use it? I learn best by example.

Here is an example taken from php.net with slight modification:

<?php
function foo(&$var)
{
    $showVar = $var++;
    echo $showVar;
}

$a=5;
foo($a);
?>

How is the above different from:

<?php
    function foo($var) // & was removed here.
{
    $showVar = $var++;
    echo $showVar;
}

$a=5;
foo($a);
?>

I got the same exact result (the value of 5) when printing $var++, but according to the documentation there, it should be 6.

What is the advantage?

In any case, I'd appreciate a very lucid and even dumbed down explanation of that the benefits of using & is when referencing something.

gitlinggun
  • 108
  • 6
  • 1
    `$showVar`, regardless of references, will always be 5. What is different is the value of `$a` in both versions AFTER you call `foo()`. – nickb Apr 25 '13 at 19:46
  • 2
    Passing by reference is a programming paradigm, independent of language. [This question](http://stackoverflow.com/questions/410593/pass-by-reference-value-in-c) has been answered. – Jason McCreary Apr 25 '13 at 19:48
  • The value of `$showVar` depends on whether you use `$var++` or `++$var` in the assignment. That's unrelated to the call by reference. – Barmar Apr 25 '13 at 19:53
  • BTW printing `$var++` will print the value of `$var` before the increment. – Populus Apr 25 '13 at 19:53

2 Answers2

3

Best to explain with code:

function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
echo $a; // 6

In this example above the value of $a can changed insed the function. Meaning if you pass by reference the function has access to a variable in the calling context. This is different to:

function foo($var)
{
    $var++;
}

$a=5;
foo($a);
echo $a; // 5

Where the param passed to the function is just a copy of the value of $a

hek2mgl
  • 133,888
  • 21
  • 210
  • 235
0

The difference is that if you don't pass it by reference, the change only happens locally within the function.

In your first scenario, if you use echo $a after calling the function, you'll see the changes made to that variable within the function. In the second scenario, you wont.

Dallas
  • 17,186
  • 21
  • 64
  • 82