user18813821
user18813821

Reputation:

Functions arguments vs use keyword argument in anonymous function?

Often we come across one point where we are using some closures in PHP and as I use Laravel for my projects closures are used so much in frameworks like in eloquent queries

So here is a scenario

$name = "john doe";

$greet = function() use ($name) {
    echo "hi " . $name;
    echo "\n";
};

$greetAgain = function($name) {
    echo "hi " . $name;
};

$greet();

$greetAgain($name);

Now the output I get is

hi john doe
hi john doe

See there is no difference at all but according to closures there are two approaches I've used one is

Passed name in function's arguments

Passed name in use keyword

But as there is no difference I just wanted to know what is the main reason behind these two different approaches for same result

Yes I also know that use keyword is used because anonymous function can not have outer scope

Also I just wanted to know when to use which one method

This question was also asked by me and it arise this question use identifier in php and how does it affect the logic

Upvotes: 1

Views: 244

Answers (1)

IMSoP
IMSoP

Reputation: 97996

The reason the two appear to do the same thing is that you have over-simplified your example, and used the function as soon as you create it. In real code, the point of creating an anonymous function would be to declare it in one place, and use it in another - for instance, to pass it as the callback to usort or array_map; or to re-use it multiple times.

It follows naturally that there are two different times you might have data that the function needs, and that's what the two parts of the declaration are for:

  • When you define the function, you can "capture" data using the use clause
  • When you execute the function, you can pass in data using the parameters

A better example that demonstrates the difference might be:

// We know the surname we want to use every time the function runs
// Maybe it actually comes from user input
// But we don't yet know what first name to use
$surname = "Smith";
$greet = function($firstname) use ($surname) {
    echo "hi " . $firstname . " " . $name;
    echo "\n";
};

// This might happen in a completely different part of the code
// We might no longer know the surname, but the closure remembers it for us
foreach ( ['John', 'Jane', 'Jimmy'] as $firstname ) {
    $greet($firstname);
}

Upvotes: 2

Related Questions