Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

closures - Access variables from parent scope in anonymous PHP function

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?

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() { ... }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

function() use ($db) {

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header [using use].

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...