Skip to content
Advertisement

Use variable by reference in arrow function

PHP 7.4 introduced Arrow functions. And it also introduced implicit by-value scope binding which eliminate the need for use keyword.

Now if we want to use a variable out of a closure’s scope by reference with a regular anonymous function we would do this:

$num = 10;
call_user_func(function() use (&$num) {
$num += 5;
});
echo $num; // Output: 15

But using an arrow function it seems impossible

$num = 10;
call_user_func(fn() => $num += 5);

echo $num; // Output: 10

So how to use $num variable by reference?

Advertisement

Answer

Reading the documentation about it, it says…

By-value variable binding
As already mentioned, arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope:

$x = 1; 
$fn = fn() => $x++; // Has no effect 
$fn(); 
var_dump($x); // int(1)

So it is not possible ATM.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement