0

I understand what both Lambda and Closure functions represent, but I don't understand the need for Closure functions.
What's the need for Closure functions if we can just pass the variable to the Lambda functions. It looks like it's easier to write the variable name when calling the function, than writing 'use' and then defining it.
For example, these two will do exactly the same:

$string = 'string'; $lambda = function($string) { echo $string; }; $lambda($string); 
$string = 'string'; $closure = function() use ($string) { echo $string; }; $closure(); 

...and in my understanding, the first block of code is Anonymous (Lambda) function, and the second one is Closure. Also, changing the variable inside the function will not affect the variable outside of it in both ways.
I've found a lot of questions about the differences, but none of them explained the need for it.
Thank you for answers.

2 Answers 2

2

The closure function is useful when you don't have control over the arguments that are being passed. For instance, when you use array_map you can't add an additional parameter, it just receives the array elements. You can use the closure to access additional variables.

$string = "foo"; $array = ["abc", "def"]; $new_array = array_map(function($x) use ($string) { return $string . $x; }, $array); 
Sign up to request clarification or add additional context in comments.

Comments

0

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // outputs helloWorld 

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.