Call by Reference in PHP
In PHP, you can pass arguments to functions by reference, allowing the function to directly modify the original variable passed as an argument. This means that changes made to the parameter inside the function will affect the original variable outside the function.
To pass an argument by reference, you use an ampersand (&) before the parameter name in both the function definition and the function call. Here's an example:
function increment(&$num) {
$num++;
echo "Inside function: $num
";
}
$num = 5;
increment($num);
echo "Outside function: $num"; // Output: Outside function: 6
In this example
- We define a function called increment() that takes a parameter $num by reference, denoted by the & symbol.
- Inside the function, we increment the value of $num by one.
- We then declare a variable $num with the value 5 outside the function.
- We call the increment() function with the variable $num as an argument.
- Since $num is passed by reference, any changes made to $num inside the function directly affect the original variable $num outside the function. So, when we echo the value of $num outside the function, it reflects the updated value 6.
In summary, when you pass an argument by reference in PHP, the function receives a reference to the original variable, allowing it to modify the variable directly. This behavior is known as call by reference. However, it's important to use call by reference judiciously, as it can lead to unexpected behavior if not used carefully.