PHP's Closure is an anonymous function. It was introduced by PHP5.3.
The syntax of closures is very simple. The only key word to be noticed is use, which means to connect closures and external variables.
-
$a =function()use($b) {
-
-
}
Several functions of closures:
1 reduce the code of foreach's loop
such as Manual http://php.net/manual/en/functions.anonymous.php Example Cart in
-
<?php
-
-
-
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);
-
};
-
-
array_walk($this->products,$callback);
-
return round($total, 2);;
-
}
-
}
-
-
$my_cart =new Cart;
-
-
-
$my_cart->add('butter', 1);
-
$my_cart->add('milk', 3);
-
$my_cart->add('eggs', 6);
-
-
-
print $my_cart->getTotal(0.05) . "\n";
-
-
?>
Here, if we modify the getTotal function, we must use foreach
2 reduce the parameters of the function
-
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 normal methods, we will inner put to html In function parameters, no matter whether it's code reading or using, it's better to use closures
3 derecursive function
-
<?php
-
$fib =function($n)use(&$fib) {
-
if($n == 0 || $n == 1) return 1;
-
return $fib($n - 1) + $fib($n - 2);
-
};
-
-
echo $fib(2) . "\n";
-
$lie =$fib;
-
$fib =function(){die('error');};
-
echo $lie(5);
Note that the use in the above question uses &, and if it is not used here & there will be an error fib(fib(n-1) cannot find the function (the type of fib has not been defined previously)
So when you want to use a closure unwinding function, you need to use the
-
<?php
-
$recursive =function ()use (&$recursive){
-
-
}
In this form
4 about delay binding
If you need to delay binding variables in use, you need to use references, otherwise you will make a copy of the definition and put it in use
-
<?php
-
$result = 0;
-
-
$one =function()
-
{ var_dump($result); };
-
-
$two =function()use ($result)
-
{ var_dump($result); };
-
-
$three =function()use (&$result)
-
{ var_dump($result); };
-
-
$result++;
-
-
$one();
-
$two();
-
$three();
Using and not using references means whether to assign when calling or when declaring