SoFunction
Updated on 2025-03-09

Closure function use {} Usage scenarios and techniques in PHP

Since there is a function that cannot access global functions, a syntax structure that can introduce the previous scope is needed, and the value of the variable in the scope when declared by the function is used through use. PHP closures may not be used frequently, but in some cases you can still consider using PHP closures to implement certain functions.

The closure of php is an anonymous function. It was introduced by PHP5.3.

When talking about closures, you have to think of anonymous functions, also called closures. Anonymous functions have no name, if you want to use it, you need to return it to a variable. Anonymous functions can declare parameters like ordinary functions, and the call methods are the same.

    $func = function( $param ) {
     echo $param;
    };
    $func( 'some string' );

    //Output:    //some string

function () use () {} syntax structure

In PHP, since there is no global function that cannot be accessed within the function, a syntax structure that can introduce the previous scope is needed, and it has a connection with the previous scope. The statement structure is as follows:

function () use () {}

Just write the variables that need to be introduced into the function and into the brackets of use, for example

<?php
$a = 1;
$closure = function () use ($a) {
    echo $a;
};
$closure();
?>

The output result is

1

Closure function() use() {} usage scenario:

1. Code to reduce the loop of foreach

&lt;?php  
// A basic shopping cart that includes some items that have been added and the quantity of each item.// There is a method to calculate the total price of all items in the shopping cart.  This method uses a closure as the 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-&gt;products[$product] = $quantity;  
    }  

    public function getQuantity($product)  
    {  
        return isset($this-&gt;products[$product]) ? $this-&gt;products[$product] :  
               FALSE;  
    }  

    public function getTotal($tax)  
    {  
        $total = 0.00;  
        $callback =  function ($quantity,$product)use ($tax, &amp;$total)  
            {  
                $pricePerItem = constant("::PRICE_" .  strtoupper($product));  
                $total += ($pricePerItem *$quantity) * ($tax + 1.0);  
            };  
        array_walk($this-&gt;products,$callback);  
        return round($total, 2);;  
    }  
}  
$my_cart =new Cart;  
// Add an entry to the shopping cart$my_cart-&gt;add('butter', 1);  
$my_cart-&gt;add('milk', 3);  
$my_cart-&gt;add('eggs', 6);  
// Make a total price, which has a sales tax of 5%.print $my_cart-&gt;getTotal(0.05) . "\n";  
// The result is 54.29  
?&gt;

If we modify the getTotal function here, we must use foreach

2 Reduce the function's parameters

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 whether it is code reading or using it, it is better to use closures.

3. Unrestoring the recursive 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";// 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 previous question uses &, if you do not use & here, an error n-1 will appear). The function cannot be found (the type of fib is not defined before)

So when you want to use closure to unloop function, you need to use

<?php  
$recursive =function ()use (&$recursive){  
// The function is now available as $recursive  

}

Such a form

4 About Delayed Binding

If you need to delay binding variables in use, you need to use a reference, otherwise you will make a copy and put it in the use when defining it.

<?php  

$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 references and not using references means whether to assign values ​​at call time or assign values ​​at declaration time

This is the article about the use scenarios and techniques of closures in PHP. This is all about this article. For more related PHP function(), use(), please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!