
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP References
Introduction
In PHP, References enable accessing the same variable content by different names. They are not like pointers in C/C++ as it is not possible to perform arithmetic oprations using them. In C/C++, they are actual memory addresses. In PHP in contrast, they are symbol table aliases. In PHP, variable name and variable content are different, so the same content can have different names. A reference variable is created by prefixing & sign to original variable. Hence $b=&$a will mean that $b is a referewnce variable of $a.
Assign By Reference
In following example, two variables refer to same value
Example
<?php $var1=10; $var2=&$var1; echo "$var1 $var2
"; $var2=20; echo "$var1 $var2
"; ?>
Output
Change in value of one will also be reflected in other
10 10 20 20
If you assign, pass, or return an undefined variable by reference, it will get created. Assigning a reference to a variable declared global inside a function, the reference will be visible only inside the function. When a value is assigned to a variable with references in a foreach statement, the references are modified too.
Example
<?php $arr=[1,2,3,4,5]; $i=&$ref; foreach($arr as $i) echo $i*$i, "
"; echo "ref = ". $ref; ?>
Output
Value of $ref stores that of last element in array
1 4 9 16 25 ref = 5
In following example, array element are references to individual variables declared before array initialization. If element is modified, value of variable also changes
Example
<?php $a = 10; $b = 20; $c=30; $arr = array(&$a, &$b, &$c); for ($i=0; $i<3; $i++) $arr[$i]++; echo "$a $b $c"; ?>
Output
Values of $a, $b and $c also get incremented
11 21 31
- Related Articles
- PHP Spotting References
- PHP Unsetting References
- PHP Objects and references
- Examples of soft references and phantom references?
- Python Weak References
- References in C++
- Create References in Perl
- Circular References in Perl
- Pointers vs References in C++
- References to Functions in Perl
- Types of References in Java
- What are method references in Java8?
- Back references in Java regular expressions
- What are circular references in C#?
- C/C++ Pointers vs Java references\n
