Reference operator:
Reference operator(&) introduced in php 4.0 version.
Why we need reference operator ?
Consider this is the scenario,
We have variable a and b. Variable a value assigned to variable b. If we are changing the variable a value frequently after the value assignment to variable b, it will not be reflected.
To overcome the above issue reference operator introduced in php.
Sample PHP Program: [without Reference operator]
[php gutter=”false”]
<?php
$a = 5;
$b = $a;
$a = 10;
echo $b;
?>
[/php]
Output:
[plain gutter=”false”]
5
[/plain]
Here we have assigned a variable a value to variable b. But after the assignment variable a value has been changed from 5 to 10. But if you print b variable, we are getting the old assigned value (5) only.
Now the above issue has been resolved using the reference operator in php,
Sample PHP program: [with Reference operator]:
[php gutter=”false”]
<?php
$a = 5;
$b = &$a;
$a = 10;
echo $b;
?>
[/php]
Output:
[plain gutter=”false”]
10 (ten)
[/plain]
Here whenever the variable value a changes it affects automatically to the already assigned variable b too.
PHP Recommended Books: