在php中返回闭包的结果?
在我的在php中返回闭包的结果?,php,Php,在我的\u调用魔术方法的某个地方,我正在调用事务,接受一个闭包: try { $that = $this $this->conn->transactional(function ($conn) use ($that, $realMethod) { $result = call_user_func([$that, $realMethod], $conn); $this->conn->exec('SET foreign_key_
\u调用
魔术方法的某个地方,我正在调用事务
,接受一个闭包
:
try {
$that = $this
$this->conn->transactional(function ($conn) use ($that, $realMethod) {
$result = call_user_func([$that, $realMethod], $conn);
$this->conn->exec('SET foreign_key_checks = 1');
});
} catch (\Exception $e) {
$this->conn->exec('SET foreign_key_checks = 1');
throw $e;
}
是否有任何方法可以从闭包内部返回$result
(或使用passbyreference等)
方法$conn->transactional
不在我的控制之下:
public function transactional(Closure $func)
{
$this->beginTransaction();
try {
$func($this);
$this->commit();
} catch (Exception $e) {
$this->rollback();
throw $e;
}
}
确实存在--在try
块中创建一个局部变量,并通过引用捕获它:
$result = null;
$that = $this;
$this->conn->transactional(function ($conn) use ($that, $realMethod, &$result) {
$result = call_user_func([$that, $realMethod], $conn);
$this->conn->exec('SET foreign_key_checks = 1');
});
return $result;
当然,这是假设
事务性的会当场调用它的参数,因为事实上,我们都会很高兴。在发布问题后马上解决了这个问题。由于某种奇怪的原因,PHPStorm给了我一个错误,让我觉得这是不可能的。谢谢