What's the purpose of using & before a functio

2020-05-24 19:52发布

I saw some function declarations like this:

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

what does the & character do?

7条回答
放我归山
2楼-- · 2020-05-24 20:22

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
查看更多
\"骚年 ilove
3楼-- · 2020-05-24 20:25

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
查看更多
闹够了就滚
4楼-- · 2020-05-24 20:25

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
查看更多
狗以群分
5楼-- · 2020-05-24 20:27

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
查看更多
一夜七次
6楼-- · 2020-05-24 20:33

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.
查看更多
smile是对你的礼貌
7楼-- · 2020-05-24 20:46

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.

查看更多
登录 后发表回答