What is Pass by Reference in PHP: Simple Explanation and Example
pass by reference means giving a function direct access to the original variable, not a copy. This allows the function to change the variable's value outside its own scope.How It Works
Imagine you have a note with a phone number. If you give a friend a copy of that note, they can change their copy but your original stays the same. This is like pass by value in PHP, where a function gets a copy of the variable.
Now, if you give your friend the original note itself, any changes they make will affect your note too. This is like pass by reference. The function gets a direct link to the original variable, so changes inside the function affect the original variable outside.
In PHP, you use an ampersand & before the parameter name in the function definition to tell PHP to pass the variable by reference.
Example
This example shows a function that doubles a number by changing the original variable using pass by reference.
<?php function doubleValue(&$number) { $number = $number * 2; } $value = 10; doubleValue($value); echo $value; // Output will be 20 ?>
When to Use
Use pass by reference when you want a function to modify the original variable directly, saving memory by avoiding copies. This is helpful when working with large data like arrays or objects.
For example, if you want to update a user's score or change settings inside a function and keep those changes after the function ends, pass by reference is useful.
Key Points
- Pass by reference lets functions change the original variable.
- Use
&before the parameter name to enable it. - It saves memory by avoiding copies of large data.
- Be careful: changes affect the original variable outside the function.