References in PHP
In PHP, you can assign the value of one variable to another:
<?php
$num1 = 1;
$num2 = $num1; // assigning
echo $num1; // 1
echo $num2; // 1
?>
With such assignment, a copy of the value of the first variable is written into the new variable. This means that the variables are not connected in any way to each other and can be changed independently. See the code example:
<?php
$num1 = 1;
$num2 = $num1;
$num2 = 2;
echo $num1; // 1 - hasn't changed
?>
It is possible, however, to make it so that not the value of the variable is copied, but its reference. In this case, when the value of one variable changes, the value of the other will also change.
To pass a value by reference, you need to put an ampersand before the variable name:
<?php
$num1 = 1;
$num2 = &$num1; // pass by reference
?>
Now changing the first variable will also change the second:
<?php
$num1 = 1;
$num2 = &$num1;
$num2 = 2;
echo $num1; // 2 - changed
?>
Similarly, if we change the first variable, the second one will also change:
<?php
$num1 = 1;
$num2 = &$num1;
$num1 = 2;
echo $num2; // 2
?>
Explain what the result of executing the code will be:
<?php
$num1 = 1;
$num2 = $num1;
$num2 = 2;
echo $num1;
echo $num2;
?>
Explain what the result of executing the code will be:
<?php
$num1 = 1;
$num2 = &$num1;
$num2++;
echo $num1;
echo $num2;
?>
Explain what the result of executing the code will be:
<?php
$num1 = 1;
$num2 = $num1;
$num1++;
$num2++;
echo $num1;
echo $num2;
?>
Explain what the result of executing the code will be:
<?php
$num1 = 1;
$num2 = &$num1;
$num1++;
$num2++;
echo $num1;
echo $num2;
?>