Home > Article > Backend Development > How do PHP functions handle variable references?
Variable passing methods in PHP functions: Value passing: The function receives a copy of the variable value, and modifications to the copy will not affect the original variable. Passing by reference: By using the & symbol, you can pass by reference, and the function can directly modify the value of the original variable.
PHP Function and Variable Reference
In PHP, when passing variables as function parameters, you need to know how to handle variables Quote. There are two types of variable references: passing by value and passing by reference.
Pass by value
By default, PHP uses pass by value, which means that the function will receive a copy of the variable value. Any modifications to this copy will not affect the value of the original variable.
function test1($a) { $a += 10; // 修改副本的值 } $a = 10; test1($a); echo $a; // 输出 10,原始值不受影响
Passing by reference
Passing by reference can be achieved by passing a variable reference using the & symbol. This will allow the function to directly modify the value of the original variable.
function test2(&$a) { $a += 10; // 修改原始变量的值 } $a = 10; test2($a); echo $a; // 输出 20,原始值被修改
Practical case
Consider a function swap()
, used to exchange the values of two variables:
function swapByValue($a, $b) { // 值传递,交换副本的值 $temp = $a; $a = $b; $b = $temp; } function swapByReference(&$a, &$b) { // 引用传递,直接交换原始变量的值 list($a, $b) = [$b, $a]; } $x = 10; $y = 20; swapByValue($x, $y); echo "x = $x, y = $y\n"; // x = 10, y = 20 swapByReference($x, $y); echo "x = $x, y = $y\n"; // x = 20, y = 10
In the first example, swapping using pass-by-value doesn't work because modifying the copy's value does not affect the original variable. In the second example, passing by reference is used to implement the exchange, thereby successfully modifying the value of the original variable.
The above is the detailed content of How do PHP functions handle variable references?. For more information, please follow other related articles on the PHP Chinese website!