Tray
Tray

Reputation: 3195

What does the & sign before the parameter name of a function do?

What does the & sign before the parameter $var do?

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

    

Upvotes: 31

Views: 27578

Answers (5)

Henrik Paul
Henrik Paul

Reputation: 67703

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.

Upvotes: 34

AvatarKava
AvatarKava

Reputation: 15443

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

Upvotes: 65

Gregor Brandt
Gregor Brandt

Reputation: 7799

This means that you are passing a variable by reference https://www.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.

Upvotes: 4

user42092
user42092

Reputation:

& 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.

Upvotes: 4

Gumbo
Gumbo

Reputation: 655239

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

Upvotes: 3

Related Questions