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() { ... }
}