Search code examples
phpclosuresvariable-variables

Passing variable variable into closure throws a parse error?


I just noticed that if you try to put a variable variable into a use list of a closure, it throws a parse error. Example code:

foreach ($array as $key => $item) {
    $$key = $item->something;
    $this->doSomething($key, function ($param) use ($item, $$key) {
        $param->foo($$key);
    });
}

The parse error is this:

Parse error: syntax error, unexpected '$', expecting '&' or variable (T_VARIABLE) in

Is there something I'm doing wrong here? Why wont it let me pass the variable variable?

If I store the variable variable's value in another variable, I can pass it normally through use, but that's not optimal for my actual case.


Solution

  • You say you don't want to save the value in another variable. But what about saving a reference to the variable? That should be functionally equivalent to your code.

    foreach ($array as $key => $item) {
        $$key = $item->something;
        $otherVar = &$$key;
        $this->doSomething($key, function ($param) use ($item, $otherVar) {
            $param->foo($otherVar);
        });
    }
    

    If this doesn't work in "your actual case", please refine the code example or explain why.