PHP References

Description

Reference type variables are actually pointer to the real data. Once two variables are pointing to the same data, you can change either variable and the other one will also update.

When you use the = (assignment) operator, PHP takes the value from operand two and copies it into operand one.

Syntax

To assign by reference, you need to use the reference operator (&) after the equals operator (=), giving =&.

Example


<?PHP//from  w ww.j  a  va2 s  .co m
$a = 10; 
$b =& $a;                                                                                                 
print $a;                                                                                   
print $b;                                                                                   

++$a; 
print $a; 
print "\n";
print $b; 
print "\n";
++$b; 
print $a; 
print "\n";
print $b; 
print "\n";
?>

The code above generates the following result.

Note

As of PHP 5, objects are passed and assigned by reference by default. Assigning an object variable is actually copying its object handle, which means the copy will reference the same object as the original.

References allow a function to work directly on a variable rather than on a copy.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone