php's closure function()use() {}

Posted by pk-uk on Thu, 30 Apr 2020 17:01:59 +0200

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.

  1. $a =function()use($b) {  
  2.    
  3. }  


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

  1. <?php  
  2. //A basic shopping cart that includes some items that have been added and the quantity of each item.  
  3. //There is a way to calculate the total price of all the items in the shopping cart. This method uses a closure as the callback function.  
  4. class Cart  
  5. {  
  6.     const PRICE_BUTTER  = 1.00;  
  7.     const PRICE_MILK    = 3.00;  
  8.     const PRICE_EGGS    = 6.95;  
  9.    
  10.     protected   $products =array();  
  11.        
  12.     public function add($product,$quantity)  
  13.     {  
  14.         $this->products[$product] = $quantity;  
  15.     }  
  16.        
  17.     public function getQuantity($product)  
  18.     {  
  19.         return isset($this->products[$product]) ? $this->products[$product] :  
  20.                FALSE;  
  21.     }  
  22.        
  23.     public function getTotal($tax)  
  24.     {  
  25.         $total = 0.00;  
  26.            
  27.         $callback =  
  28.             function ($quantity,$product)use ($tax, &$total)  
  29.             {  
  30.                 $pricePerItem = constant(__CLASS__ ."::PRICE_" .  
  31.                     strtoupper($product));  
  32.                 $total += ($pricePerItem *$quantity) * ($tax + 1.0);  
  33.             };  
  34.            
  35.         array_walk($this->products,$callback);  
  36.         return round($total, 2);;  
  37.     }  
  38. }  
  39.    
  40. $my_cart =new Cart;  
  41.    
  42. //Add items to cart  
  43. $my_cart->add('butter', 1);  
  44. $my_cart->add('milk', 3);  
  45. $my_cart->add('eggs', 6);  
  46.    
  47. //Print out the total price, including 5% sales tax  
  48. print $my_cart->getTotal(0.05) . "\n";  
  49. // The result is 54.29  
  50. ?>  


Here, if we modify the getTotal function, we must use foreach

2 reduce the parameters of the function

  1. function html ($code ,$id="",$class=""){  
  2.    
  3. if ($id !=="")$id =" id = \"$id\"" ;  
  4.    
  5. $class = ($class !=="")?" class =\"$class\"":">";  
  6.    
  7. $open ="<$code$id$class";  
  8.    
  9. $close ="</$code>";  
  10.    
  11. return function ($inner ="")use ($open,$close){  
  12.    
  13. return "$open$inner$close";};  
  14.    
  15. }  
  16. 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

  1. <?php  
  2.     $fib =function($n)use(&$fib) {  
  3.         if($n == 0 || $n == 1) return 1;  
  4.         return $fib($n - 1) + $fib($n - 2);  
  5.     };  
  6.    
  7.    echo $fib(2) . "\n";// 2  
  8.    $lie =$fib;  
  9.    $fib =function(){die('error');};//rewrite $fib variable   
  10.    echo $lie(5);// error   because $fib is referenced by closure  


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

  1. <?php  
  2. $recursive =function ()use (&$recursive){  
  3. // The function is now available as $recursive  
  4. }  


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

  1. <?php  
  2. $result = 0;  
  3.    
  4. $one =function()  
  5. { var_dump($result); };  
  6.    
  7. $two =function()use ($result)  
  8. { var_dump($result); };  
  9.    
  10. $three =function()use (&$result)  
  11. { var_dump($result); };  
  12.    
  13. $result++;  
  14.    
  15. $one();   // outputs NULL: $result is not in scope  
  16. $two();   // outputs int(0): $result was copied  
  17. $three();   // outputs int(1)  


Using and not using references means whether to assign when calling or when declaring

Topics: PHP