Home » Php » php – What's the purpose of using & before a function's argument?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

I saw some function declarations like this:

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

what does the & character do?

How to&Answers:

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

Answer:

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

Answer:

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.

Answer:

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

Answer:

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

Answer:

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.

Answer:

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