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:

JavaScript

But using an arrow function it seems impossible

JavaScript

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:

JavaScript

So it is not possible ATM.

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