简体   繁体   English

这两个函数在php中有什么区别?

[英]What is the difference between these two functions in php?

These function statements are confusing me. 这些函数语句使我感到困惑。

I'm new to php, help me to understand these functions: 我是php的新手,请帮助我了解以下功能:

function addFive($num)
{
$num += 5;
}

function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";

first echo outputs 10 Second echo outputs 16 第一回波输出10第二回波输出16

What is the difference between these 2 functions? 这两个功能有什么区别?

There are two types of call: 呼叫有两种:

1) Call by value: addFive($num) 1)按值调用: addFive($num)

2) Call by reference: addSix(&$num) 2)通过引用调用: addSix(&$num)

In first case, you are just passing value of the variable. 在第一种情况下,您只是传递变量的值。

Hence, only value gets modified keeping original variable untouched. 因此,只有值被修改,而原始变量不变。

In second case, you are passing reference to the variable, hence the original value gets modified. 在第二种情况下,您正在传递对变量的引用,因此原始值会被修改。

The first function passes the argument by value - in other words, it's copied into the function, and any change you perform on it will be on the local copy. 第一个函数按值传递参数-换句话说,它被复制到函数中,并且您对它执行的任何更改都将在本地副本上。

The second function passes the argument by reference (note the & before it in the function's signature). 第二个函数通过引用传递参数(在函数签名中注意&之前)。 This means the variable itself is passed, and any modification you perform on it will survive beyond the function's scope. 这意味着将传递变量本身,并且您对其执行的任何修改都将保留在函数范围之外。

& is used to pass address of an variable in second function declaration "addSix(&$num) {}" &用于在第二个函数声明“ addSix(&$ num){}”中传递变量的地址

In second function while calling addSix( $orignum ); 在第二个函数中,同时调用addSix($ orignum); updation of value is done on address of "$orignum" 价值的更新是在地址“ $ orignum”上完成的

whereas in first function updation is done on "$num" 而在第一个函数中,更新是在“ $ num”上完成的

第一个函数在您的数字上加5,第二个函数在您的数字上加6 $num+=6表示$num= $num+6第一个函数在Call by value起作用,第二个函数在Call by reference起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM