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() { ... } } 
                Yes, use a closure: functionName($someArgument, function() use(&$variable) { $variable = "something"; }); Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & . It's new!
As of PHP 7.1, these variables must not include superglobals, $this , or variables with the same name as a parameter.
To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword.
Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With