PHP References

In this chapter you will learn:

  1. What is a reference variable
  2. Syntax for PHP reference variable
  3. Example - Using reference type variables
  4. Note for PHP reference type

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  j a  v a2s .  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.

Next chapter...

What you will learn in the next chapter:

  1. What is a constant and why it is useful
  2. Syntax to define a constant
  3. Note for PHP constant
  4. Example - Create a constant
  5. Example - Create a constant case-insensitive
  6. Example - is constant defined
  7. Example - constant function to get constant value
  8. Example - use Math constant to calculate circle area
Home » PHP Tutorial » PHP Data Types
PHP Data Types
PHP Boolean
PHP Integer
PHP Float
PHP Data Type Cast
PHP Automatic Type Conversion
PHP Super globals
PHP References
PHP Constants