Home >Backend Development >PHP Tutorial >How to pass parameters by value in php function?
In the previous article, we learned what parameters are, how to create a function and learned about formal parameters and actual parameters. If necessary, please read "What do the formal parameters and actual parameters of php functions mean?" 》. This time we take a deeper look at parameters and introduce passing by value in passing parameters to functions.
There are four ways to pass parameters to a function, namely value passing, reference passing, default parameters and variable length parameters. Today we will introduce how to pass parameters by value.
Let’s first look at a small example.
<?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 = 5, $y = 7
In this example, we can see that inside the function, the value is indeed exchanged, but outside the function, the value does not change.
Through this small example. We also have a general understanding of passing parameters by value, and I will introduce it in detail below.
Passing by value is the default value passing method for functions in PHP, also known as "Copy value passing
". As the name suggests, the value transfer method will copy the value of the parameter and then transfer it to the formal parameter of the function. Therefore, manipulating the values of parameters within a function does not affect parameters outside the function. Therefore, if you don't want a function to modify the value of a parameter, you can pass it by value.
Just like the above example, inside the function, the value is indeed exchanged, but outside the function, the value does not change. So we can say that passing a function by value is just passing a copy of the variable. So if you want the function to be able to operate on external parameters of the function, you need to use reference passing.
The php knowledge you want is here → →php video tutorial
The above is the detailed content of How to pass parameters by value in php function?. For more information, please follow other related articles on the PHP Chinese website!