Functional PHP 5.3 Part i-what is Anonymous Functions and Closures?

Source: Internet
Author: User
Tags php framework php software vars

One of the most exciting features of PHP 5.3 are the first-class support for anonymous functions. Heard them referred to as closures or lambdas as well. There ' s a lot of meaning behind these terms so let's straighten it all out.

What is the difference between Anonymous Functions, Lambdas, and Closures?

You'll see the terms "anonymous functions", "Lambdas", and "closures" thrown around in reference to the new features of PH P 5.3. Even the the redirects to The difference between ' lambda ' and ' anonymous function '? None, for all intents and purposes they be and words for the same concept which is a descendant of lambda calculus. L Anguages with anonymous functions consider functions to being first-class value types, just like integers or Booleans. Anonymous functions can thus is passed as arguments to another function or even returned by a function. Let's make it concrete in PHP:

View Plaincopy to Clipboardprint?
  1. <?php
  2. $lambda = function () {
  3. echo "I am an anonymous function,
  4. aka A lambda!<br/> ";
  5. };
  6. $anonymousFunction = $lambda;
  7. $anonymousFunction ();
  8. output:i am an anonymous function, aka a lambda!
  9. function Ncallsto ($n, $function) {
  10. For ($i = 0; $i < $n; $i + +) {  
  11. $function ();
  12. }
  13. return function () { echo "I am also an anonymous function!<br/>";};
  14. }
  15. $anotherAnon = Ncallsto (3, $anonymousFunction);
  16. Output:
  17. I am an anonymous function, aka a lambda!
  18. I am an anonymous function, aka a lambda!
  19. I am an anonymous function, aka a lambda!
  20. $anotherAnon ();
  21. Output:i am also an anonymous function!
  22. ?>

Notice How we do not assign a name to the function, we assigned a function to be the value of a variable. Just like a string or any other primative. We then assign it to another variable. The function is just a value, it has no name, and hence the term "anonymous function". We then create a regular function Named&NBSP; ncallsto  that takes-Arguments,&NBSP; $n Span class= "Apple-converted-space" > being the number of times to make a call To $function  an anonymous function.

The existance of Higher-order functions opens the door for techniques Likemap/reducenext post. nCallsTo is a higher-order function on the accounts:1) it takes a function as an argument, and 2) it returns a function as a Value. Higher-order functions Open the doors for techniques as map/reduce and deserves a post in itself. The point was lambdas and anonymous functions is the same things:functions , which is values.

If anonymous functions is values, what is does PHP consider their type to be? Let's find out:

View Plaincopy to Clipboardprint?
    1. <?php
    2. $lambda = function () { echo "anonymous function";};
    3. Echo GetType ($lambda).  ' <br/> ';
    4. Output:object
    5. Echo Get_class ($lambda).  ' <br/> ';
    6. Output:closure
    7. ?>
On the Closure object in PHP 5.3

What is a closure? So far it ' s a misnomer. We Haven ' t actually spotted a closure even though PHP assigns all anonymous functions the type Closure . Since we haven ' t actually seen a closure yet, let's take a look at one:

View Plaincopy to Clipboardprint?
  1. <?php
  2. function Letmeseeaclosure () {
  3. $aLocalNum = 10;
  4. return function () use (&$aLocalNum) { return + +$aLocalNum;};
  5. }
  6. $aClosure = Letmeseeaclosure ();
  7. echo $aClosure ();
  8. Output:11
  9. echo $aClosure ();
  10. Output:12
  11. $anotherClosure = Letmeseeaclosure ();
  12. echo $anotherClosure ();
  13. Output:11
  14. echo $aClosure ();
  15. Output:13
  16. echo $aLocalNum;
  17. notice:undefined variable:alocalnum<br>?>

Chew on this for a minute. Do you spot the funny business?$aLocalNumis a local variable defined within the scope of the Plain-old function&NBSP; letmeseeaclosure . With the New , use   Syntax the Variable&NBSP; $aLocalNum  is bound or&NBSP; closed Over  to create the closure. This allows the returned Closure to retain a reference to $aLocalNum , even After&NBSP; $aLocalNum  falls out of lexical scope when the function returns. The notice error occurs when trying to Reference&NBSP; $aLocalNum Span class= "Apple-converted-space" > directly from outside of the function ' s scope.

To recap, the terms, ' lambda ' or ' anonymous function ' refer to the same concept:functions that is values. Closures refer to a related, but different concept:the lifetime of a variable that's ' closed over ', or in PHP 5.3&NBSP; use ' d, by a closure, was bound to the lifetime, Or extent, the closure. &NBSP; Anonymous functions  that is constructed with The  Use  keyword is Also&NBSP; closures .  as mentioned, in PHP 5.3, anonymous functions is typed As&NBSP; Closure  and the three words Has, so far, been thrown about. The high-order bit to take away are an understanding, PHP 5.3 now includes language features for anonymous functions an D closures.

More on functional PHP 5.3

If you're interested in PHP software development your should subscribe to our feed. Upcoming Parts to the This series:

    • Part 1-the differences between closures, lambdas, and anonymous functions.
    • Part 2-getting down and dirty with functional programming:callbacks, function types, and map reduce.
    • Part 3-dynamically invoke Lambdas, functions, and methods with Is_callable, Call_user_func, and Call_user_func_array.
    • Part 4-we ' ll exploit the powers of XDebug to profiles common uses of anonymous functions to understand their performance Trade-offs.
    • Part 5-a First-hand look at how recess 5.3, a RESTful PHP framework, are using functional concepts to achieve simple flex Ibility.

Functional PHP 5.3 Part i-what is Anonymous Functions and Closures?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.