在匿名PHP函数中从父作用域访问变量 [英] Access variables from parent scope in anonymous PHP function

查看:102
本文介绍了在匿名PHP函数中从父作用域访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数来做一些脏工作记录事务,但是匿名函数范围似乎没有注册父作用域 $ db $ value 变量。如何将变量传递到闭包?

I want to write a function that does some dirty work logging a transaction, but the anonymous function scope does not seem to register the parent scope $db and $value variables. How can I pass the variables into the closure?

讽刺的是,SO标签closures没有非常准确地描述PHP版本...?

Ironically, the SO tag 'closures' does not describe the PHP version of it very accurately...?

class controller
{
    function submit()
    {
        $db = new database();
        $result = $db->execute_tx(function() {
            $db->insert_model_a($value_a); // ERROR: $db is non-object
            $db->insert_model_b($value_b);
        });
    }
}

class database
{
   function execute_tx($atomic_action)
   {
        try
        { 
            $this->start();
            $atomic_action();
            $this->commit();
            // etc..
        }
        catch(...)
        { 
            $this->rollback();
            // etc..
        } 
        finally
        {
            // etc..
        }
   }

   function insert_model_a() { ... }
   function insert_model_b() { ... }
}


推荐答案

使用使用关键字将变量绑定到函数的作用域。

Use the use keyword to bind variables into the function's scope.

function() use ($db) {


$ b b


闭包也可以从父作用域继承变量。任何这样的变量必须在函数头中声明[使用 use ]。

http://www.php.net/manual/en/functions.anonymous.php

这篇关于在匿名PHP函数中从父作用域访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆