Alex
Alex

Reputation: 68046

What's the purpose of using & before a function's argument?

I saw some function declarations like this:

function boo(&$var){
 ...
}

what does the & character do?

Upvotes: 40

Views: 18959

Answers (7)

Ajonetech
Ajonetech

Reputation: 23

If any function starts with ampersand(&), It means its call by Reference function. It will return a reference to a variable instead of the value.

function reference_function( &$total ){
  $extra = $total + 10;
}

$total = 200;
reference_function($total) ;
echo $total; //OutPut 210

Upvotes: -3

Darryl E. Clarke
Darryl E. Clarke

Reputation: 7637

The ampersand ( & ) before a variable ( & $foo ) overrides pass by value to specify that you want to pass the variable by reference instead.

For example if you have this:

function doStuff($variable) {
     $variable++;
}

$foo = 1;

doStuff($foo);
echo $foo; 
// output is '1' because you passed the value, but it doesn't alter the original variable

doStuff( &$foo ); // this is deprecated and will throw notices in PHP 5.3+
echo $foo; 
// output is '2' because you passed the reference and php will alter the original variable.

It works both ways.

function doStuff( &$variable) {
     $variable++;
}

$foo = 1;

doStuff($foo);
echo $foo; 
// output is '2' because the declaration of the function requires a reference.

Upvotes: 2

jerjer
jerjer

Reputation: 8770

you are passing $var as reference, meaning the actual value of $var gets updated when it is modified inside boo function

example:

function boo(&$var) {
   $var = 10;
}

$var = 20;
echo $var; //gets 20
boo($var);
echo $var //gets 10

Upvotes: 1

alex
alex

Reputation: 490303

It is pass by reference.

If you are familiar with C pointers, it is like passing a pointer to the variable.

Except there is no need to dereference it (like C).

Upvotes: 2

cambraca
cambraca

Reputation: 27835

Basically if you change $var inside the function, it gets changed outside. For example:

$var = 2;

function f1(&$param) {
    $param = 5;
}

echo $var; //outputs 2
f1($var);
echo $var; //outputs 5

Upvotes: 27

Matthew
Matthew

Reputation: 48294

It's a pass by reference. The variable inside the function "points" to the same data as the variable from the calling context.

function foo(&$bar)
{
  $bar = 1;
}

$x = 0;
foo($x);
echo $x; // 1

Upvotes: 65

SLaks
SLaks

Reputation: 887479

It accepts a reference to a variable as the parameter.

This means that any changes that the function makes to the parameter (eg, $var = "Hi!") will affect the variable passed by the calling function.

Upvotes: 6

Related Questions