0

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).

5
  • pass the value into a constructor for A and use that? Commented Oct 25, 2018 at 11:55
  • Can you not pass $b across as a parameter of the foo method? Is there any reason you don't want to do this? Commented Oct 25, 2018 at 11:57
  • Why would you ever want to use a class this way? Either pass parameters to a class or make the variable it's self global outside of the class. Though it's best to pass the parameter. Commented Oct 25, 2018 at 12:04
  • The thing is, this an overly simplified example, the actual code I'm dealing with has dozens of these global variables and methods… So I'd rather avoid any solution consisting of editing a number of method calls. Commented Oct 25, 2018 at 12:04
  • @Difster The codebase is as it is, with dozens of global variables, I'm just moving this call inside a closure because it's what happens when my router calls it (I'm currently moving from if (isset($_GET["?page"])) routing to proper routing with Slim) Commented Oct 25, 2018 at 12:10

1 Answer 1

1

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

I just found out about this, I was about to self-answer the same! Thanks anyway :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.