I'm using PHP 7.1.11
Consider the first code snippet with assigning NULL to the reference :
<?php
$a = 1;
$b =& $a;
var_dump($a);
echo "<br>";
var_dump($b);
echo "<br>";
$a = NULL;
var_dump($a);
echo "<br>";
var_dump($b);
?>
Output of above program is as below :
int(1)
int(1)
NULL
NULL
Consider second code snippet destroying the reference using unset language construct:
<?php
$a = 1;
$b =& $a;
var_dump($a);
echo "<br>";
var_dump($b);
echo "<br>";
unset($a);
var_dump($a);
echo "<br>";
var_dump($b);
?>
Output of above program is as below :
int(1)
int(1)
Notice: Undefined variable: a
NULL
int(1)
As per my knowledge a reference is an alias, which allows two different variables to write to the same value. In other words, references are means to access the same variable content by different names.
So, it's expected to change the content of both the variables if one of the variables contains reference of another variable.
The above concept works well when I assign NULL value to the reference but not working when I unset the reference.
- Isn't the thing setting variable value to NULL and unsetting the variable i.e. destroying the variable using unset have different meanings in PHP?
- What's the exact reason behind this weird behavior?
- How these two processes are different?
- Why they are producing different outputs?