tags:

views:

1054

answers:

6

Hey

Just a quick and no doubt easy question. I'm pretty new to PHP and am looking through some existing code. I have tried to find the answer to my question on google, but to no avail.

Can somebody please let me know what the '&' sign before the parameter $var does??

function setdefault(&$var, $default="")
{
  if (! isset($var))
  {
    $var = $default;
  }
}
+3  A: 

It’s indicating that the parameter is passed by reference instead of by value.

Gumbo
+16  A: 

Passes it by reference.

Huh? Passing by reference means that you pass the address of the variable instead of the value. Basically you're making a pointer to the variable.

http://us.php.net/language.references.pass

AvatarKava
+1  A: 

& means pass-by-reference; what that code does is check whether the variable passed to the function actually exists in the global scope. Without the & it'd try to take a copy of the variable first, which causes an error if it doesn't exist.

Ant P.
+6  A: 

It means that the function gets the reference to the original value of the argument $var, instead of a copy of the value.

Example:

function add(&$num) { $num++; }

$number = 0;
add($number);
echo $number; // this outputs "1"

If add() would not have the ampersand-sign in the function signature, the echo would output "0", because the original value was never changed.

Henrik Paul
+2  A: 

This means that you are passing a variable by reference http://ca3.php.net/language.references.pass. Simply this means the function is getting an the actual variable and not a copy of the variable. Any changes you make to that variable in the function will be mirrored in the caller.

gbrandt
A: 

Thank you for all the answers guys - makes a lot of sense now!

Tray
You should not respond by posting a new answer unless you are providing one. If you need to thank the community or add more information, either edit your original post or post a comment to your original post.
TheTXI