dsfsfsfsfs55656 2014-07-17 19:04
浏览 102
已采纳

在php中返回Closure的结果?

Somewhere in my __call magic method I'm invoking transactional, accepting a Closure:

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;
}

Is there any way to return $result from inside the Closure (or using pass by reference, etc.)?

Method $conn->transactional is not under my control:

public function transactional(Closure $func)
{
    $this->beginTransaction();
    try {
        $func($this);
        $this->commit();
    } catch (Exception $e) {
        $this->rollback();
        throw $e;
    }
}
  • 写回答

1条回答 默认 最新

  • dongzhi6146 2014-07-17 19:06
    关注

    Sure there is -- create a local variable inside the try block and capture it by reference:

    $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;
    

    Of course this assumes that transactional will call its argument on the spot, since that's the case indeed we can all be happy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿请人帮写个安卓系统下禁止装软件及禁止拷入文件的程序
  • ¥100 用 H.265 对音视频硬编码 (CUDA)
  • ¥20 mpich安装完成后出问题
  • ¥15 multisim仿真
  • ¥15 stm32循迹小车代码问题
  • ¥15 输入一堆单词,使其去重输出
  • ¥15 qc代码,修改和添加东西
  • ¥50 Unity的粒子系统使用shadergraph(内置管线)制作的一个顶点偏移shader,但是粒子模型移动时,顶点也会偏移
  • ¥15 如何用python处理excel的数据(极值标准化)
  • ¥15 三向应力状态求剪应力