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

sylbru
  • 1,461
  • 1
  • 11
  • 19
  • pass the value into a constructor for A and use that? – Barry Oct 25 '18 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? – RobFos Oct 25 '18 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. – Difster Oct 25 '18 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. – sylbru Oct 25 '18 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) – sylbru Oct 25 '18 at 12:10

1 Answers1

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();
});
Eakethet
  • 682
  • 1
  • 5
  • 18