Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables from parent scope in anonymous PHP function

Tags:

closures

php

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() { ... } } 
like image 271
Jake Avatar asked Feb 23 '13 15:02

Jake


People also ask

How can you pass a local variable to an anonymous function in PHP?

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!

Which statement is not allowed in anonymous function in PHP?

As of PHP 7.1, these variables must not include superglobals, $this , or variables with the same name as a parameter.

How do you define a variable accessible in function in PHP script?

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.

How can access global variable inside function in PHP?

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.


1 Answers

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

like image 53
salathe Avatar answered Oct 08 '22 04:10

salathe