The problem of PHP closure function

$name = function(){
    $a="x";
        $name2=function() use ($a){
        return "".$a;
        };
        return $name2;
};

echo $name () (); / / Why do I have to write two parentheses here to output?

Php
Jan.03,2022

because your above code uses two = function () {} , defining two nested closures. Isn't it reasonable to pair two closures with two parentheses.


nested closure. The return value of $name () is a closure function, and $name () () is the inner closure of the call


. The

function is also a value, an object, like 123,1.341, "str", which is not difficult.

$name is a function:

function(){
$a="x";
    $name2=function() use ($a){
    return "".$a;
    };
    return $name2;
};

$name () is the return value of $name for this function (above function) (that is, the internally returned function $name2):

function() use ($a){
        return "".$a;
        };

$name () () is the call to the internal $name2 corresponding function. The result, of course, is the return value of this statement return "I like to eat". $a;


There is no doubt that

calls $name this closure function requires the use of $name () .

but what is the value returned by $name () ? $name2 is returned, while $name2 is a closure function, while calling $name2 requires $name2 () .

so echo $name () () is equivalent to:

  

because the return value is a method

Menu