Home >Backend Development >PHP Tutorial >PHP closure variable scope

PHP closure variable scope

藏色散人
藏色散人forward
2019-12-30 13:21:172456browse

In projects, it is inevitable to encounter the form of closures. So in closures, what is the scope of variables? Here are a few simple examples.

#e1

function test_1()
{
    $a = 'php';
    $func =  function ($b) use ($a)
    {
       // $a = 'java';
        echo $b.'_'.$a;
    };
    return $func;
}
$test = test_1();
$test('hello');

The above result will output hello_php, then you can see that $a is passed as a variable through use to the anonymous function func as a parameter; if you remove $ a = 'java' comment, then the above result will output hello_java

e2: Rewrite the above function as

function test_2()
{
    $a = 'php';
    $func =  function ($b) use ($a)
    {
       // $a = 'go';
        echo $b.'_'.$a;
    };
    $a = 'java';
    return $func;
}
$test = test_2();
$test('hello');

The above result will output hello_php. The description is in test_2 When $a is assigned a value for the second time, it is not passed to the func function.

Similarly, if $a = 'go' is removed; then the above result will output hello_go

e3: Now add a reference to $a

function test_3()
{
    $a = 'php';
    $func =  function ($b) use (&$a)
    {
        //$a = 'go';
        echo $b.'_'.$a;
    };
    $a = 'java';
    return $func;
}
$test = test_3();
$test('hello');

The above result will output hello_java, indicating that the value of variable a will be passed to the function func when the address is referenced.

Similarly if $a = 'go' is removed;

The above result will output hello_go;

The above three simple tests clearly explain the closure The scope of the parameters inside.

When address reference is not used, the variable value of the anonymous function will not change as the external variable changes. (The meaning of closure)

After using the address reference, the parameter value will be changed by the parameter value of the external function.

For more PHP related knowledge, please visit PHP Tutorial!

The above is the detailed content of PHP closure variable scope. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete