Php closures (Closure) anonymous functions _ PHP Tutorial

Source: Internet
Author: User
Php closures (Closure) anonymous functions. Php closures (Closure) the description of anonymous functions this article mainly introduces PHP anonymous functions introduced by php5.3, that is, Closure, and the function of closures, which are very detailed, the php Closure (Closure) anonymous function details

This article mainly introduces the PHP anonymous function introduced by php5.3, that is, the function of the Closure (Closure) and the function of the Closure, which is very detailed. we recommend it to friends who need it.

Php closures (Closure), that is, anonymous functions, are introduced by PHP5.3.

The syntax of closure is very simple. Note that only use is the keyword. use is the connection closure and external variables.

The code is as follows:


$ A = function () use ($ B ){}

A simple example is as follows:

The code is as follows:


Function callback ($ fun ){
$ Fun ();
}
$ Msg = "Hello, everyone ";
$ Fun = function () use ($ msg ){
Print "This is a closure use string value, msg is: $ msg.
/N ";
};
$ Msg = "Hello, everybody ";
Callback ($ fun );

The result is: This is a closure use string value, msg is: Hello, everyone.
/N

In the new closure syntax of PHP, we use the external variables defined by the closure. Here we use the external variable $ msg. after the definition is complete, the value is changed. after the closure is executed, the original value is output. For the basic type parameter passed by passing values, the value of the closure use is determined when the closure is created.

Small applications:

The code is as follows:


/**
* A counter generator using closures
* The reference here is an example of introducing closures in python...
* We can consider this as follows:
* 1. each time the counter function is called, a local variable $ counter is created and initialized to 1.
* 2. create a closure that generates a reference to the local variable $ counter.
* 3. the counter function returns the created closure and destroys local variables. However, a closure references $ counter,
* It will not be recycled. Therefore, we can understand that the closure returned by the counter function carries a free state
* Variable.
* 4. since each counter call creates an independent $ counter and closure, the returned closure is independent of each other.
* 5. execute the returned closure to auto-increment the Free State variable carried by it and return it. The result is a counter.
* Conclusion: This function can be used to generate mutually independent counters.
*/
Function counter (){
$ Counter = 1;
Return function () use (& $ counter) {return $ counter ++ ;};
}
$ Counter1 = counter ();
$ Counter2 = counter ();
Echo "counter1:". $ counter1 ()."
/N ";
Echo "counter1:". $ counter1 ()."
/N ";
Echo "counter1:". $ counter1 ()."
/N ";
Echo "counter1:". $ counter1 ()."
/N ";
Echo "counter2:". $ counter2 ()."
/N ";
Echo "counter2:". $ counter2 ()."
/N ";
Echo "counter2:". $ counter2 ()."
/N ";
Echo "counter2:". $ counter2 ()."
/N ";
?>

Function of closure

1. reduce the code for foreach loop
Example Cart in the manual http://php.net/manual/en/functions.anonymous.php

The code is as follows:


// A basic shopping cart, including some added items and the quantity of each item.
// One method is used to calculate the total price of all items in the shopping cart. This method uses closure as the callback function.
Class Cart
{
Const price_butter= 1.00;
Constprice_milk = 3.00;
Const maid = 6.95;
Protected $ products = array ();
Public function add ($ product, $ quantity)
{
$ This-> products [$ product] = $ quantity;
}
Public function getQuantity ($ product)
{
Return isset ($ this-> products [$ product])? $ This-> products [$ product]:
FALSE;
}
Public function getTotal ($ tax)
{
$ Total = 0.00;
$ Callback =
Function ($ quantity, $ product) use ($ tax, & $ total)
{
$ PricePerItem = constant (_ CLASS _. ": PRICE _".
Strtoupper ($ product ));
$ Total + = ($ pricePerItem * $ quantity) * ($ tax + 1.0 );
};
// Use a user-defined function to call back each element in the array.
Array_walk ($ this-> products, $ callback );
Return round ($ total, 2 );;
}
}
$ My_cart = new Cart;
// Add entries to the shopping cart
$ My_cart-> add ('butter ', 1 );
$ My_cart-> add ('milk', 3 );
$ My_cart-> add ('eggs', 6 );
// Calculate the total price, with a sales tax of 5%.
Print $ my_cart-> getTotal (0.05). "\ n ";
// The result is 54.29
?>

If we transform the getTotal function, we must use foreach.

2. Reduce function parameters

The code is as follows:


Function html ($ code, $ id = "", $ class = ""){
If ($ id! = "") $ Id = "id = \" $ id \"";
$ Class = ($ class! = "")? "Class = \" $ class \ ">": "> ";
$ Open = "<$ code $ id $ class ";
$ Close =" ";
Return function ($ inner = "") use ($ open, $ close ){
Return "$ open $ inner $ close ";
};
}

If we use the usual method, we will put inner in the html function parameters. in this way, whether it is code reading or using, it is better to use closures.

3. remove recursive functions

The code is as follows:


$ Fib = function ($ n) use (& $ fib ){
If ($ n = 0 | $ n = 1) return 1;
Return $ fib ($ n-1) + $ fib ($ n-2 );
};
Echo $ fib (2). "\ n"; // 2
$ Lie = $ fib;
$ Fib = function () {die ('error') ;}; // rewrite $ fib variable
Echo $ lie (5); // error because $ fib is referenced by closure

Note that the use in the above question is used. if the function is not used here, the error fib (n-1) cannot be found (the fib type is not defined previously)

So when you want to use the closure to remove the cyclic function, you need to use

The code is as follows:


$ Recursive = function () use (& $ recursive ){
// The function is now available as $ recursive
}

This form.

4. Delayed binding

If you need to delay binding the variables in use, you need to use references. Otherwise, a copy will be made during definition and put into use.

The code is as follows:


$ Result = 0;
$ One = function ()
{
Var_dump ($ result );
};
$ Two = function () use ($ result)
{
Var_dump ($ result );
};
$ Three = function () use (& $ result)
{
Var_dump ($ result );
};
$ Result ++;
$ One (); // outputs NULL: $ result is not in scope
$ Two (); // outputs int (0): $ result was copied
$ Three (); // outputs int (1)

When reference is used or when reference is not used, it indicates whether the value is assigned during call or declaration.

Do you have a new understanding of PHP anonymous functions, that is, closure functions? I hope this article will give you some tips and hope you will like them.

The description of Closure anonymous functions this article mainly introduces PHP anonymous functions introduced by php5.3, that is, Closure and the function of closures. this is very detailed...

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: info-contact@alibabacloud.com 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.