PHP Call By Reference
PHP supports passing parameters by reference. This technique is called "Call by Reference". By reference means that when a variable is passed as an argument to a function, its memory address is passed to the function instead of its value.
Syntax
The syntax for calling a function by reference is as follows:
function functionName(&$arg1, &$arg2, ...){
//function body
}
Example
Here's an example that demonstrates how to pass a parameter by reference in PHP:
<?php
function swap(&$x,&$y) {
$temp=$x;
$x=$y;
$y=$temp;
}
$a = 5;
$b = 10;
echo "Before Swap: a=".$a." b=".$b."<br/>";
swap($a,$b);
echo "After Swap: a=".$a." b=".$b."<br/>";
?>
Output
The output of the above example will be:
Before Swap: a=5 b=10
After Swap: a=10 b=5
Explanation
In the above example, the swap()
function accepts two arguments $x
and $y
by reference. Inside the function, the values of $x
and $y
are swapped using a temporary variable $temp
. The original values of $a
and $b
are then swapped using swap($a,$b)
.
Use
The &
operator is used to denote a variable as a reference variable in PHP. Reference variables are often used to return multiple values from a function.
Important Points
- In PHP, Call by Reference can be used with functions as well as methods.
- When you pass a variable as an argument to a function, a new copy of that variable is created inside the function.
- However, when you pass a variable by reference, the original variable is passed to the function and changes made to the parameter inside the function affect its value outside the function.
Summary
PHP supports Call By Reference, which helps to pass parameters by reference to the function instead of just their values. This allows changes made to the parameters inside the function to affect their value outside the function. Reference variables are often used to return multiple values from a function.