print "This is a closure use string value, msg is: $msg.
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.
/**
* A counter generator using closures
* This is actually based on the example of closures introduced 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, so we can understand that the closure returned by the function counter carries a free state
* 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
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;
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 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
The code is as follows:
function html($code , $id="", $class=""){
if ($id !== "") $id = " id = "$id"" ;
$class = ($class !== "")? " class ="$class">":">";
$open = "<$code$id$class";
$close = "$code>";
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 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 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
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
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.
http://www.bkjia.com/PHPjc/966918.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/966918.htmlTechArticleDetailed explanation of PHP's closure (Closure) anonymous function This article mainly introduces to you the PHP anonymous function introduced in php5.3 Functions, that is, closures (Closure), and the functions of closures are very detailed. This...