Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pass reference parameters PHP?
In PHP, you can pass parameters by reference using the & symbol before the parameter name in the function definition. This allows the function to modify the original variable instead of working with a copy.
Syntax
To pass a parameter by reference, prefix the parameter with & in the function definition ?
function functionName(&$parameter) {
// Modify the original variable
}
Example
Here's how to pass a reference parameter to modify the original variable ?
<?php
function referenceDemo(&$number){
$number = $number + 100;
return $number;
}
$number = 900;
echo "The actual value is = " . $number . "<br>";
$result = referenceDemo($number);
echo "The modified value is = " . $result . "<br>";
echo "Original variable now = " . $number;
?>
The actual value is = 900 The modified value is = 1000 Original variable now = 1000
Pass by Value vs Pass by Reference
Compare the difference between passing by value and by reference ?
<?php
// Pass by value
function byValue($num) {
$num = $num * 2;
return $num;
}
// Pass by reference
function byReference(&$num) {
$num = $num * 2;
return $num;
}
$value1 = 10;
$value2 = 10;
echo "Before: value1 = $value1, value2 = $value2<br>";
byValue($value1);
byReference($value2);
echo "After: value1 = $value1, value2 = $value2<br>";
?>
Before: value1 = 10, value2 = 10 After: value1 = 10, value2 = 20
Conclusion
Pass by reference using & allows functions to modify original variables directly. This is useful when you need to update the caller's variable or work with large data structures efficiently.
Advertisements
