Closures, Lambdas, and Anonymous Functions


Lambdas and ClosuresBeginning with PHP 5.3, the anonymous function, became available to developers as a means of improving flexibility and increasing the number of tools at our fingertips to build powerful PHP applications.  What I have been seeing a lot of as I read through documentation is more frequent use of terms like lambda, closure,  or anonymous function, and sometime the terms are often used interchangeably, so let’s take a deeper look into  what all of these things are and what differences, if any, there are between them.

Lambda Defined

The simplest way to define a lambda is to say that it is a function that doesn’t have a name.  This is most likely why it is also referred to as an “anonymous function”…verrry catchy isn’t it?  In its most basic form, a lambda might look something like this:

A lambda is a construct of the language and it is the exact same thing as an anonymous function,  so using these 2 terms interchangeably is perfectly acceptable.  Knowing both names for this is important for the simple fact that a developer could use either term when documenting code.  For no other reason than it is shorter to write, I will use the term “lambda” from here on out.

Although the simplicity of the example above has only been available since PHP 5.3, anonymous functions have been available through the  create_function() function since PHP4, so while not new, strictly speaking, it is now much easier to use.

Closure Defined

The PHP manual does not draw any distinction between a closure and anonymous function (although the RFC for it does), and interestingly, the only mention of the term lambda on that page of the manual is in an user’s example.  That said, if we dig a little deeper, it seems that there is a difference whereby we really cannot say that every lambda is also automatically a closure.

The most probable reason that PHP uses the terms closure and anonymous function with no distinction between them is that PHP handles all anonymous functions through its  Closure class. This means that for PHP, whether a function is technically a closure or strictly a lambda doesn’t affect how PHP handles it.

From the technical perspective, the real difference between the lambda and the closure lies in how the function interacts with its surrounding environment.  Closures interact with the surrounding environment by attaching a variable(s) to the lambda.  This binding or “closing over” of the variable is what makes it a closure.  In PHP, we attach the data to the lambda with the  use keyword.  Let’s look at an example:

In the code above,  the lambda uses the $myVar variable which is assigned from outside of the local scope of the lambda.  The  use keyword makes  $myVar available to the lambda.

Uses for a Lambda/Closure

So, why would we ever need a function with no name?  I mean, without a name we cannot call it from other places in the app, so what good is it?  There are fair questions, particularly considering that we have gone so far in PHP applications without closures.  I guess the best way to think about using it is for a function you only need at the moment of execution.  Perhaps you need to execute a simple function as you walk over an array or something similar.  A lambda or closure may do the trick.  The main use cases for these will typically revolve around some relatively simple function only needed once to process a given set of instructions.  I can also see where a lambda would be handy in prototyping to get some code up and running in a hurry when trying to get a proof of concept done.

Updates in PHP 5.4

When PHP 5.4 was release, there was a specific update for lambdas / closures included.  As of PHP 5.4, the pseudo-variable  $this can be accessed with  use keyword, where previously it was not possible to do this.  This definitely gives closures more utility and ease of use inside of a class method, where closures can come in handy from time to time.

Arguments Against

Lambdas and Closures do offer some convenience and expanded functionality to developers, but there are also some potential pitfalls.  For every article or comment I have read about how these things improve readability, I see something that makes the opposite claim.  Without question, if you start nesting lambdas, things can get messy quickly, and future maintenance will become problematic.  I guess a good rule of thumb would be that the more complicated your function becomes, the less suitable a lambda is for the job.

I can also see where there is a potential pitfall for unit testing an application.  That is not to say that you cannot unit test an app with lambdas & closures, because you can. However, each of these lambdas is another potential point of failure or variance and this might make it a little harder to figure out what is going wrong.

Conclusion

Lambdas & Closures are like anything else in PHP, there is a time, a place, and a use case for them.  They have the ability to simplify and speed up development when used properly, but as with most other things, misuse and overuse of them can make your code difficult to maintain later on.  Once you have used them a few times, it gets easier to discern when it is a good time to use one, and when you are better off using a named function instead.  Ultimately, you have to balance speed & convenience of using a closure or lambda against making your code unreadable, untestable, and just generally difficult to deal with.  I hope you found this helpful. If you didn’t know what these terms meant, or what the differences between them are, hopefully this post was able to shed a little light on the subject.

-Andy

, ,

  1. #1 by Silver Moon on February 21, 2013 - 11:33 pm

    I find lambdas most useful when implementing callbacks to quickly add some custom functionality to a class, without extending them.

    • #2 by Andy (@phpAndy) on February 22, 2013 - 7:09 am

      Appreciate the feedback. I use them sporadically, and it is always helpful to see how others are doing it. Thanks!

  2. #3 by Ashesh Bharadwaj on February 22, 2013 - 2:34 am

    Thanls Andy for the simple and clear explanation.

    I have not been using them so far but would certaily consider them if the need arise.

  3. #5 by Charlyarg on February 22, 2013 - 10:47 am

    Thanks for the concepts clarification. As Silver Moon said for me the anonymous functions are great for using as callback parameters to another function. The whole “a function in a variable” thing sounds powerful. And of course you got stuff in other languages like jquery to prove this point. Anyway I agree that a deep nesting can make code unreadable.

    • #6 by Andy (@phpAndy) on February 22, 2013 - 11:54 am

      I appreciate the feedback very much, Thanks for stopping by!

  4. #7 by Boabramah Ernest on February 22, 2013 - 11:51 am

    I have been using them recently for data validations. $this->validation->post(‘user_name’,function($val){$val->minLenght(5)->notEmpty()}); It is a great thing but as u said, know when to use it properly

    • #8 by Andy (@phpAndy) on February 22, 2013 - 11:54 am

      Thanks for giving your feedback and visiting the blog!

  5. #9 by Wil Moore III on February 24, 2013 - 4:34 pm

    Short, concise closures can go a long way. For example: http://stackoverflow.com/a/10660002/128346

    • #10 by Andy (@phpAndy) on February 24, 2013 - 4:36 pm

      Great example, thanks for reading and commenting!

Comments are closed.