thelolcat
thelolcat

Reputation: 11615

use() statement on anonymous functions

Is it a bad practice to use it?

Because people say that global variables are bad practice and the use thing brings variables from outside into the functions, so it's like global

This is how it looks

$a = 1;
$func = function() use($a){
  print $a;
};

Upvotes: 3

Views: 1514

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

Any arguments defined in the "use" arguments for an anonymous function use the value at the time when the anonymous function is defined; so they must exist at that point; but they don't need to be passed (or even exist in the caller scope) when the function is called.

function myFunctionCreator() {
    $a = 1; // Must exist for the `use` clause
    $func = function() use($a){
        echo $a, PHP_EOL;
    };
    return $func;
}

$myFunc = myFunctionCreator();
$a = 2;

$myFunc(); // echoes 1 (value of $a at the point where the function was created)

As you can see from the above example, $a has a value of 1 at the point where the function is defined, and even though a variable with the same name exists at the point when the function called, it is the original $a (with the value 1) that is used in the function call.


Arguments defined in the main argument definition need not exist when the function is defined, but the values must be passed as arguments to the function at the point when it is called.

function myFunctionCreator() {
    $a = 1; // Need not exist, and will be ignored
    $func = function($a) {
        echo $a, PHP_EOL;
    };
    return $func;
}

$myFunc = myFunctionCreator();
$value = 2;

$myFunc($value);  // echoes 2 (value of $a explicitly passed to the function call
                  //           at the time it is executed)

So the behaviour of the two types is quite different, and their purpose when combined provides a degree of flexibility that is quite different


As Rizier123 has mentioned in his comment, arguments passed to an anonymous function as "standard" can have defaults, typehints, etc, whereas "use" arguments cannot.

function myFunctionCreator() {
    $func = function(array $dataset = [1,2,3]) {
        foreach($dataset as $value) {
            echo $value, PHP_EOL;
        }
    };
    return $func;
}

$myFunc = myFunctionCreator();
$value = ['a','b','c'];

$myFunc($value);
$myFunc();
$myFunc(['x','y','z']);

Or (as the third call shows, arguments can be passed directly.

Andy of these applied to a "use" argument will result in a parse error

Upvotes: 4

Related Questions