Home > Backend Development > PHP Tutorial > Detailed explanation of PHP's closure (Closure) anonymous function, detailed explanation of closure function_PHP tutorial

Detailed explanation of PHP's closure (Closure) anonymous function, detailed explanation of closure function_PHP tutorial

WBOY
Release: 2016-07-13 10:06:27
Original
817 people have browsed it

Detailed explanation of PHP’s closure (Closure) anonymous function, detailed explanation of closure function

PHP’s closure (Closure) is an anonymous function, which was introduced in PHP5.3.

The syntax of closure is very simple. The only keyword that needs attention is use, which connects closure and external variables.

Copy code The code is as follows:

$a = function() use($b) {}

A simple example is as follows:

Copy code 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 PHP’s new open closure syntax, we use use to use variables defined outside the closure. Here we use the external variable $msg. After it is defined, its value is changed. After the closure is executed, the original value is output. For basic type parameters passed by value, the value of the closure use is determined when the closure is created.

The mini-applications are as follows:

Copy code The code is as follows:

/**
* A counter generator using closures
* This is actually based on the example of introducing closures in python...
* We can think about it this way:
* 1. Each time the counter function is called, a local variable $counter is created, initialized to 1.
* 2. Then create a closure, which generates a reference to the local variable $counter.
* 3. The function counter returns the created closure and destroys the local variable, but at this time there is a reference to $counter from the closure,
* It will not be recycled. Therefore, we can understand that the closure returned by the function counter carries a free
* Variable.
* 4. Since each call to counter creates an independent $counter and closure, the returned closures are independent of each other.
* 5. Execute the returned closure, increment the free state variable it carries and return it, and the result is a counter.
* Conclusion: This function can be used to generate 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";
?>

The role of closure

1. Reduce the code of foreach loop
For example, the example Cart in the manual http://php.net/manual/en/functions.anonymous.php

Copy code The code is as follows:

// A basic shopping cart, including some added items and the quantity of each item.
// One of the methods is used to calculate the total price of all items in the shopping cart. This method uses a closure as a callback function.
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.95;
                              $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 user-defined function to perform callback processing on each element in the array
         array_walk($this->products, $callback);
          return round($total, 2);;
}
}
$my_cart = new Cart;
// Add items to shopping cart
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);
// Print the total price, including 5% sales tax.
print $my_cart->getTotal(0.05) . "n";
// The result is 54.29
?>

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

2. Reduce function parameters

Copy code 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 into the html function parameters, so that it is better to use closures whether it is reading or using the code.

3. Unlock the recursive function

Copy code 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 use in the above question uses &. If & is not used here, an error will occur. fib(n-1) cannot find the function (the type of fib was not defined previously)

So when you want to use closure to cancel the loop function, you need to use

Copy code The code is as follows:

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

This form.

4. Delay binding

If you need to delay binding the variables in use, you need to use references, otherwise a copy will be made and placed in use when defining

Copy code 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)

Using a reference or not using a reference indicates whether the value is assigned when calling or when it is declared

Have you guys gained a new understanding of PHP’s anonymous functions, which are closure functions? I hope this article can give you some tips and I hope you like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/959107.htmlTechArticleDetailed explanation of php's closure (Closure) anonymous function, closure function detailed explanation of php's closure (Closure), which is anonymous Function, introduced in PHP5.3. The syntax of closure is very simple, but you need to pay attention to the following...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template