
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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