PHP: access a variable from a class/method, both defined inside the same closure

38 Views Asked by At

The following code is working as expected:

$b = 42;
var_dump("b: " . $b);

class A
{
    function foo()
    {
        global $b;
        var_dump("b: " . $b);
    }
}

$instance = new A();
$instance->foo();

The foo method is able to access $b thanks to the global keyword.

However, if I move all of this in a closure, $b is not a “global” variable anymore, and it doesn't work (with or without the global statement):

call_user_func(function () {
    $b = 42;
    var_dump("b: " . $b);

    class A
    {
        function foo()
        {
            global $b;
            var_dump("b: " . $b);
        }
    }

    $instance = new A();
    $instance->foo();
});

How can I edit this code so that the method has access to the ”closure top-level” (not global) variables?

I was unable to find the same question on SO, feel free to close this if there is a duplicate (not something about the use keyword which has nothing to do with my issue here).

1

There are 1 best solutions below

1
Eakethet On BEST ANSWER

With "globalization" of var $b before storing value into it, it works fine for me. Snippet here:

call_user_func(function () {
    global $b;
    $b = 42;
    var_dump("b: " . $b);

    $instance = new class
    {
        function foo()
        {
            global $b;
            var_dump("b: " . $b);
        }
    };

    $instance->foo();
});