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
Reference assignment operator in PHP to assign a reference?
In PHP, the reference assignment operator =& allows you to create a reference to a variable rather than copying its value. When variables are linked by reference, changes to one variable automatically reflect in the other.
Syntax
To assign a reference, use the reference assignment operator −
$variable1 = &$variable2;
This creates a reference where both $variable1 and $variable2 point to the same memory location.
Example
Here's how reference assignment works in practice −
<?php
$nextValue = 100;
$currentValue = &$nextValue;
echo "Next Value = " . $nextValue . "<br>";
echo "Current Value = " . $currentValue . "<br>";
// Change the original variable
$nextValue = 45000;
echo "After changing nextValue:<br>";
echo "Next Value = " . $nextValue . "<br>";
echo "Current Value = " . $currentValue . "<br>";
?>
Next Value = 100 Current Value = 100 After changing nextValue: Next Value = 45000 Current Value = 45000
How It Works
When you use $currentValue = &$nextValue, both variables become aliases pointing to the same memory location. Any modification to either variable affects both, since they reference the same data.
Key Points
- Reference assignment creates aliases, not copies
- Changes to any referenced variable affect all aliases
- Use
&symbol before the source variable name - Both variables share the same memory location
Conclusion
The reference assignment operator =& in PHP creates variable aliases that point to the same memory location. This allows multiple variables to share and modify the same data, making it useful for efficient memory usage and variable linking.
