简体   繁体   中英

Using global inside a closure in PHP

Somehow, the following results in NULL. Why is this the case? I find it important to know, because the use statements does not support variable variables.

function a() {
    $a = "a";
    $aa = function() {
        global $a;
        var_dump($a);
    };
    $aa();
}
a();

The value is NULL because there is no global with name $a .

The following would print "global":

$a = "global"; // global variable initialization

function a() {
    $a = "a";
    $aa = function() {
        global $a;
        var_dump($a);
    };
    $aa();
}
a();

You can write this :

function a() {
    $a = "a";
    function b() {
        global $a;
        var_dump($a);
    };
    $aa = "b";
    $aa();
}
a();

Maybe you can make a reference to the variable variables.

function a() {

    $a = "b";
    $b = "variable";

    $ref = &$$a;

    $aa = function() use ($ref) {
        var_dump($ref);
    };
    $aa();
}
a();

which outputs: string(8) "variable"

Variable $t is the variable variable you can access with $$a . Note that inside the function a() , $t is never used, so should be what you want.

$t = 3;
$a = 't';
function a()
{
    global $a, $$a;
    $x = $$a;
    $b = function()  use ($x) {
        echo $x;
    };
    $b();
}
a();

The code prints 3 .

global $a access a global variable called $a . It is not the local variable in the function a . Since you have never initialized a global variable called $a , it is NULL.

In order for local variables to be usable inside an anonymous function, they must be captured using a use clause. Local variables can either be captured by value or by reference.

If you want to capture by value (which means the value of the local variable $a is copied into the closure at the time it's defined):

function a() {
    $a = "a";
    $aa = function() use ($a) {
        var_dump($a);
    };
    $aa();
}
a();

If you want to capture by reference (which means inside the closure it directly references the variable $a ):

function a() {
    $a = "a";
    $aa = function() use (&$a) {
        var_dump($a);
    };
    $aa();
}
a();

In this case both would be the same. But if you modified the variable after the closure was created, and before it is run, it would give a different result (the capture by value would still have the previous value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM