Difference between a lambda function and a closure (in PHP)?
Asked Answered
C

5

15

Chapter 2 of "Magento PHP Developer's Guide" states:

Zend Framework 2 uses 100% object-oriented code and utilizes most of the new features of PHP 5.3, namely namespaces, late static binding, lambda functions and closures.

While the post What is the difference between a 'closure' and a 'lambda'? has some answers (such as, that a lambda is just an anonymous function, and that a closure is a function which can access variables not in its parameter list), seems to be specific to the Python programming language (with some mention of the Scheme programming language). For instance, according to the post, in Python, it seems, there can be closures which are not lambdas, and lambdas which are not closures.

However, I am interested in the PHP programming language, not Python. One of the answers below seems to point out that in PHP all closures are lambdas, which conflicts with what the post relating to Python states.

It seems to me, that these concepts vary in the particulars from language to language, and I am interested in PHP, hence this post.

All of this is confusing. While I would assume that lambda functions in general are just unnamed functions, the following Wikipedia article says more about closures:

http://en.wikipedia.org/wiki/Closure_%28computer_science%29

although has no examples in PHP.

Chalmers answered 12/11, 2013 at 14:0 Comment(2)
You could try to search before asking; here's the same question: #221158Kano
The following article from Philip Brown provide a good summary of what are the differences between a closure and a lambda function. Good examples are also provided.Pentylenetetrazol
W
26

A closure is a lambda function in php that encapsulates variables so they can be used once their original references are out of scope.

A closure is a lambda function, but a lambda function is not a closure unless you specify the use keyword.

This is a much better answer: https://mcmap.net/q/15026/-what-is-the-difference-between-a-39-closure-39-and-a-39-lambda-39

Wary answered 12/11, 2013 at 14:8 Comment(6)
Thanks. What I found there is a generic answer. What is written in that thread is that a lambda function is just an anonymous function, whereas a closure is any function which accesses variables which can be found outside of the function(which does not match your answer above that each closure is a lambda function, because according to the aforementioned thread a closure can have a name, as long as it accesses the global scope).Chalmers
Is this correct for PHP though? I would imagine that each languages define these concepts in a slightly different way, and my question is specific to PHP. What is the exact definition of these in PHP? Thanks.Chalmers
@JohnSonderson: the concepts of "closure" and "anonymous function" are independent of languagePrance
@Prance Concept and implementation can be two different things. For example PHP functions are not automatically able to access the environment of the global scope, and the PHP manual specifically defines closure object type as "anonymous functions" in the first line of php.net/manual/en/class.closure.phpEmergence
Another important difference in PHP's implementation of closures is that the environment provided to the function is not made of reference variables by default. wiki.php.net/rfc/closures#references_vs_copiesEmergence
@gh123man: +1, nicely put! I like yours a lot more than that "much better" answer you linked. (Especially with the "PHP" tag of the question.)Pneumoencephalogram
K
9

Lambda function is assigned to a variable or passed to another function as parameter. Closures make use of variables from outside theirs scope.

Using lambdas

Because the function has no name, you can’t call it like a regular function. Instead you must either assign it to a variable or pass it to another function as an argument.

// Anonymous function
// assigned to variable
$greeting = function () {
  return "Hello world";
}

// Call function
echo $greeting();
// Returns "Hello world"

To so use the anonymous function, we assign it to a variable and then call that variable as a function.

You could also pass the function to another function, like this:

// Pass Lambda to function
function shout ($message){
  echo $message();
}

// Call function
shout(function(){
  return "Hello world";
});

What is a Closure?

A Closure is essentially the same as a Lambda apart from it can access variables outside the scope that it was created.

For example:

// Create a user
$user = "Philip";

// Create a Closure
$greeting = function() use ($user) {
  echo "Hello $user";
};

// Greet the user
$greeting(); // Returns "Hello Philip"

As you can see above, the Closure is able to access the $user variable, because it was declared in the use clause of the Closure function definition.

If you were to alter the $user variable within the Closure, it would not effect the original variable. To update the original variable, we can append an ampersand. An ampersand before a variable means this is a reference and so the original variable is also updated.

For example:
// Set counter
$i = 0;
// Increase counter within the scope
// of the function
$closure = function () use ($i){ $i++; };
// Run the function
$closure();
// The global count hasn't changed
echo $i; // Returns 0

// Reset count
$i = 0;
// Increase counter within the scope
// of the function but pass it as a reference
$closure = function () use (&$i){ $i++; };
// Run the function
$closure();
// The global count has increased
echo $i; // Returns 1

This text is part of Philip Brown article at >> culttt.com. You can find some more examples there.

Knox answered 4/1, 2017 at 6:36 Comment(0)
M
3

There is a PHP-specific article with detailed explanation and code examples: http://www.ibm.com/developerworks/library/os-php-5.3new2/

Broken link warning: as of 2014-10-18, the above link is 404. I copied the article from Google cache and placed here:

If you find the original document re-appearing anywhere, please let me know.

Masorete answered 7/5, 2014 at 15:57 Comment(1)
The original link of the article has reappeared.Hamner
P
0

Closure actually means if you use a variable its value will be used inside a closed function without to update its value outside of it. You have to use the reference operator & instead, if you want to update the value of the used variable but as a normal argument.

Thats the powerful use for it you can in/decrement things like this or create fibonaccis or iterate generator functions easier without regular functions that rely on the global namespace.

Lambdas don't support use hence they cannot enclose variables from the outer scope. Also closures can be cached hence it improves compiling perfomances.

Preterhuman answered 17/9, 2016 at 16:48 Comment(0)
B
0

Function

  • A piece of code which takes one or more inputs in the form of arguments, do some processing and returns a value.
  • It should have a name, to be called by it's name when needed.
  • Multiple functions can be wrapped inside a Class (To allow having multiple functions with the same name and much more).

Anonymous function

  • A function that has no name.
  • It does not necessarily need to create a closure.

Lambda

  • An anonymous function that can be assigned to variables or passed to other functions as an argument.
  • It can’t be called like a regular function since it has no name, This it must either get assign it to a variable or pass it to another function as an argument. Thus it becomes a Lambda function.
  • It is useful because they it's a throw away function that you can use once at certain place only without the need to reuse it in many places.

Closure

  • Is the same as a Lambda. But it can access variables from the outside scopewithout using global variables. (it can capture the state of its surrounding environment).
  • Can work around variable scope restrictions in a clean way using the "use" syntax. (Basically it's an anonymous function with the use syntax).
  • It's not created only for anonymous functions.
  • It's smarter than Lambda in the sense that it have the ability to interact with variables from the outside environment.     

         

Biagio answered 3/9, 2017 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.