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

前端 未结 6 1980
醉酒成梦
醉酒成梦 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:27

    Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.

    So I made a code example with early binding of a variable (= copying):

    ";
        echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."
    "; }; echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."
    "; echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."
    "; $closureExampleEarlyBinding(); echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."
    "; echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."
    "; /* this will output: Before executing $closureExampleEarlyBinding() $a = 1 Before executing $closureExampleEarlyBinding() $b = 2 Inside $closureExampleEarlyBinding() $a = 2 Inside $closureExampleEarlyBinding() $b = 3 After executing $closureExampleEarlyBinding() $a = 1 After executing $closureExampleEarlyBinding() $b = 2 */ ?>

    Example with referencing a variable (notice the '&' character before variable);

    ";
        echo "Inside \$closureExampleReferencing() \$b = ".$b."
    "; }; echo "Before executing \$closureExampleReferencing() \$a = ".$a."
    "; echo "Before executing \$closureExampleReferencing() \$b = ".$b."
    "; $closureExampleReferencing(); echo "After executing \$closureExampleReferencing() \$a = ".$a."
    "; echo "After executing \$closureExampleReferencing() \$b = ".$b."
    "; /* this will output: Before executing $closureExampleReferencing() $a = 1 Before executing $closureExampleReferencing() $b = 2 Inside $closureExampleReferencing() $a = 2 Inside $closureExampleReferencing() $b = 3 After executing $closureExampleReferencing() $a = 2 After executing $closureExampleReferencing() $b = 3 */ ?>

提交回复
热议问题