有没有办法从闭包外的闭包中访问变量?例如,我想在闭包之外访问$wallet
:
public function generate()
{
$this->ssh->run([
'~/Web/gatewayd/gateway generate_wallet'
], function($line) use ($fn)
{
$wallet = data $line.PHP_EOL;
});
return json_decode($wallet);
}
我试过这个解决方案,但我觉得这既不起作用也不好:
public function generate()
{
$wallet = null;
$this->ssh->run([
'~/Web/gatewayd/gateway generate_wallet'
], function($line) use ($wallet)
{
$wallet = $line;
});
return json_decode($wallet);
}
答案 0 :(得分:2)
试试:
public function generate()
{
$wallet = null;
$this->ssh->run([
'~/Web/gatewayd/gateway generate_wallet'
], function($line) use ($fn, &$wallet)
{
$wallet = data $line.PHP_EOL;
});
return json_decode($wallet);
}
答案 1 :(得分:1)
嗯,理想的解决方案是,如果$this->ssh->run()
返回回调函数的返回值。即:
$wallet = $this->ssh->run(..., function ($data) { return $data; });
缺乏这一点,你可以做的最好的是use
并带有参考:
$this->ssh->run(..., function ($data) use (&$wallet) { $wallet = $data; });
^
echo $wallet;