- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<?php $var1=10; $var2=&$var1; echo "$var1 $var2\n"; $var2=20; echo "$var1 $var2\n"; ?>
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.
<?php $arr=[1,2,3,4,5]; $i=&$ref; foreach($arr as $i) echo $i*$i, "\n"; echo "ref = ". $ref; ?>
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
<?php $a = 10; $b = 20; $c=30; $arr = array(&$a, &$b, &$c); for ($i=0; $i<3; $i++) $arr[$i]++; echo "$a $b $c"; ?>
Values of $a, $b and $c also get incremented
11 21 31
- 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
- C/C++ Pointers vs Java references
- What are circular references in C#?
- Back references in Java regular expressions
- What are method references in Java8?