I was reading about arrow functions in php documentions and I came across this code
fn&($x = 42) => $x;
fn(&$x) => $x;
what is the difference between these two statements and what they do ?
I was reading about arrow functions in php documentions and I came across this code
fn&($x = 42) => $x;
fn(&$x) => $x;
what is the difference between these two statements and what they do ?
in the second you use &$x and that's passing a variable by reference. it calls reference by value
so the $x out of the function will change if you do something in the function.
here the final value of $a is 5:
$a = 5;
$y = fn ($x) => $x++;
$y($a);
echo $a;//5
but in reference by value, the final value of $a changed and it's 6:
$a = 5;
$y = fn (&$x) => $x++;
$y($a);
echo $a;//6
So you can see in reference by value, the original value of the variable can be changed
& sets a reference to the variable
fn($x = 42) : is a function with one or 0 parameter, if 0, default value 42
fn(&$x) : is a function with one parameter passed as reference, meaning if changed in the function, the new value of $x will be pass in the main.