1

Does PHP support useing a local variable inside the scope of a Closure even when this one is created via Closure::fromCallable() ?

Usually I'd do

$value = 'foobar';
$callback = function() use (&$value) {
    $value .= ' string';
    return $value;
};
var_export($callback());  // prints 'foobar string'

But how do I obtain the same when having more complex code?

class A
{
    public function __construct()
    {
        $value = 'foobar';
        $callback = Closure::fromCallable([ $this, 'myCallable' ]);

        var_export( $callback() );
    }

    protected function myCallable()
    {
        $value .= ' string';
        return $value;
    }
}

I know in this case I could just pass the value as callable argument, but I am writing because of curiosity about how PHP works.

Also, yes, it's pretty nonsense to use $value inside myCallable without having declared it anywhere. But still, it's more about curiosity than correctness

I already tried $callback = Closure::fromCallable([ $this, 'myCallable' ]) use ($value); but it fails with a syntax error.

Shouldn't the fromCallable method support passing the variables that we want in the closure's scope, replacing the functionality of the use statement?

I can't find any insight in functions.anonymous or closure.fromcallable.

Kamafeather
  • 8,663
  • 14
  • 69
  • 99
  • I can see a problem is that `use` allows access to the scope encapsulating the call - but a closure could be defined in method A (so the `use` is defined in A) and then called in method B - so which scope does it use. – Nigel Ren Jul 23 '19 at 15:52
  • Legit observation ... – Kamafeather Jul 23 '19 at 16:18

1 Answers1

1

What if you can resolve it this way :

class A
{
    private $value;

    public function __construct()
    {
        $this->value = 'foobar';
        $callback = Closure::fromCallable([ $this, 'myCallable'  ]);

        var_export( $callback() );
    }

    protected function myCallable()
    {
        $this->value .= ' string'; 
        return $this->value;
    }
}
Kamafeather
  • 8,663
  • 14
  • 69
  • 99
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43