In the previous article, we learned about passing parameters by value in passing parameters to functions. If you need it, please read "How to pass parameters by value in PHP functions?" 》. This time we will introduce you to reference passing in passing parameters to functions. You can refer to it if you need it.
Let’s first look at a small example to help us understand reference passing.
<?php function swap(&$a, &$b){ echo '函数内,交换前 $a = '.$a.', $b = '.$b.'<br>'; $temp = $a; $a = $b; $b = $temp; echo '函数内,交换后 $a = '.$a.', $b = '.$b.'<br>'; } $x = 5; $y = 7; echo '函数外,交换前 $x = '.$x.', $y = '.$y.'<br>'; swap($x, $y); echo '函数外,交换后 $x = '.$x.', $y = '.$y; ?>
The output result is
函数外,交换前 $x = 5, $y = 7 函数内,交换前 $a = 5, $b = 7 函数内,交换后 $a = 7, $b = 5 函数外,交换后 $x = 7, $y = 5
In this example, we can see that inside the function, the values are indeed exchanged, and outside the function, the values are also exchanged.
This is the difference between passing by reference and passing parameters by value in the previous article.
Parameter reference passing is to copy the memory address of the parameter and then pass it to the formal parameter of the function. Both parameters and formal parameters point to the same memory address. Therefore, the function's operation on the formal parameters will affect the parameters outside the function.
Passing by reference is to pass the memory address of the parameter to the formal parameter of the function. Therefore, the parameters and formal parameters point to the same memory address. At this time, all operations within the function will affect the values of parameters outside the function. The method of reference transfer is to add a <strong>&</strong>
symbol, as shown below:
function name (&参数1, &参数2, ..., &参数3) { ... }
At the same time, this symbol is also reference transfer
and The difference between value passing parameters
.
That’s it for passing by reference. If you want to know anything else, you can click here. → →php video tutorial
The above is the detailed content of How to pass parameters by reference in php function?. For more information, please follow other related articles on the PHP Chinese website!