i am learning php and i have to solve an exercise, it is about passing value by reference in php. I have to justify the output, i want you guys to correct my answer.
I submited the code below there are two functions and four variable we pass the value by reference from the SecondFunction to the FirstFunction.
there are five answers or outputs the exercise is to get the right output and explain and justify the answer.
Thank you very much.
<?php
function FirstFunktion(&$param){
$param = $param * 2;
}
function SecondFunktion($param){
$param = $param / 2;
}
$var1 = 10;
$var2 = 20;
$var3 = 30;
$var4 = 0;
$var4 = &$var1;
echo "var4: $var4<br />"; // output: var4: 10
FirstFunktion($var4);
echo "var1: $var1<br />"; // output: var1: 20
if ($var4 > $var2){
$var4 = $var2;
}else{
$var4 = &$var3;
}
SecondFunktion($var4);
echo "var4: $var4<br />"; // output: var4: 30
FirstFunktion($var3);
echo "var1: $var1<br />"; // output: var1: 20
echo "var2: $var2<br />"; // output: var2: 20
?>
My answers
output: var4: 10 here we have value 10 because we got the value of $var1 = 10 by passing the value by reference $var4 = &$var1
output: var1: 20 here we run $var4 through the FirstFunction that multiply the value of $var4 10 * 2 then we output $var1 the value is the same for both $var1 and $var4
output: var4: 30 here we have an if which is not true then the output is else $var3 and $var4 have now the same value 30 then we run $var4 through SecondFunction 30/2=15 by reference will be automatically changed through the FirstFunction 15*2=30 the final result is 30
output: var1: 20 here is tricky we run the FirstFunktion($var3) but has no effect on $var1 ($var1 remained unchanged and doesn't get the value of $var3 and $var4)
output: var2: 20 here $var2 is always the same and doesn't get any reference as we initialised $var2 = 20