In PHP, what is a closure and why does it use the “use” identifier?

前端 未结 6 1970
醉酒成梦
醉酒成梦 2020-11-22 00:45

I\'m checking out some PHP 5.3.0 features and ran across some code on the site that looks quite funny:

public function getTotal($tax)
{
    $tot         


        
6条回答
  •  终归单人心
    2020-11-22 01:38

    The function () use () {} is like closure for PHP.

    Without use, function cannot access parent scope variable

    $s = "hello";
    $f = function () {
        echo $s;
    };
    
    $f(); // Notice: Undefined variable: s
    
    $s = "hello";
    $f = function () use ($s) {
        echo $s;
    };
    
    $f(); // hello
    

    The use variable's value is from when the function is defined, not when called

    $s = "hello";
    $f = function () use ($s) {
        echo $s;
    };
    
    $s = "how are you?";
    $f(); // hello
    

    use variable by-reference with &

    $s = "hello";
    $f = function () use (&$s) {
        echo $s;
    };
    
    $s = "how are you?";
    $f(); // how are you?
    

提交回复
热议问题