What is the difference between passing function arguments by value and by reference in PHP?
When passing function arguments by value in PHP, a copy of the variable is passed to the function, so any changes made to the variable within the function do not affect the original variable outside of the function. When passing arguments by reference, the function receives a reference to the original variable, so any changes made to the variable within the function will affect the original variable outside of the function.
// Passing arguments by value
function increment($num) {
$num++;
return $num;
}
$number = 5;
$newNumber = increment($number);
echo $number; // Output: 5
echo $newNumber; // Output: 6
// Passing arguments by reference
function incrementByReference(&$num) {
$num++;
}
$number = 5;
incrementByReference($number);
echo $number; // Output: 6
Related Questions
- What is the recommended method for sending personalized emails to multiple recipients in PHP, instead of using a do-while loop?
- What are the potential pitfalls of using single quotes in PHP when accessing POST variables?
- What potential issue is the user facing with generating and replacing random words in their Hangman project using PHP?