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
What is Pass By Reference and Pass By Value in PHP?
In PHP, you can pass arguments to functions using two methods: pass by value (default) and pass by reference. Understanding the difference is crucial for effective programming.
By default, PHP uses pass by value, meaning the function receives a copy of the variable. Changes inside the function don't affect the original variable. However, pass by reference allows the function to modify the original variable by using the ampersand (&) symbol.
Pass By Reference
To pass a variable by reference, prepend an ampersand (&) to the parameter name in the function definition. This allows the function to modify the original variable −
<?php
function calculate(&$a){
$a++;
}
$a = 5;
calculate($a);
echo $a;
?>
6
Here, the variable $a is passed by reference to the calculate() function. When the function increments $a, it modifies the original variable, so the output shows the changed value.
Pass By Value
With pass by value (default behavior), the function receives a copy of the variable. Changes inside the function don't affect the original −
<?php
function calculate($a){
$a++;
echo $a . "<br/>";
}
$a = 5;
calculate($a);
echo $a;
?>
6 5
The function increments its local copy of $a (showing 6), but the original variable remains unchanged (still 5).
Key Points
- Use ampersand (&) only in function definition, not in function calls
- Pass by reference is useful when you need to modify multiple variables in one function
- Pass by value is safer as it prevents accidental modification of variables
- PHP 5.4+ deprecated using & in function calls
Conclusion
Choose pass by reference when you need to modify original variables, and pass by value when you want to protect your data from unintended changes. Understanding both concepts helps you write more efficient and safer PHP code.
