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

PHP closure variable scope

藏色散人
Release: 2023-04-08 06:54:01
forward
2458 people have browsed it

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');
Copy after login

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');
Copy after login

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');
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template