Does PHP support use
ing 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