PHP: Can anonymous functions inside an associative array access other members of the array?

In the following example, is it possible to access the value of 'str' from an anonymous function?

$foo = array( 'str' => 'THIS IS A STRING', 'fn' => function () { // is it possible from within here to access 'str'? } ); 
+4
source share
2 answers

if $foo defined in the global namespace, you must have access to it through $GLOBALS['foo']['str'] (or make it available through the global $foo; construct). If this is not the case (local var, parameter, member variable, ...), you should pass it (as a link!) To the anonymous function:

 $foo = array( 'str' => 'THIS IS A STRING', 'fn' => function () use(&$foo) { echo $foo['str']; } ); 
+2
source

I found another way to do this without using global variables:

 <?php $arr = array("a" => 12, "b" => function($num) { $c = $num * 2; return $c; }); echo $arr["b"]($arr["a"]); ?> 

Note the weird syntax for ending an array index call using the method parentheses. By passing $arr["a"] as a parameter, you can access this value (I think you could follow the link too).

If you were not to pass anything into an anonymous function, you would call it the following:

 $arr["b"](); 

If you do not include the brackets of the method, this will not work.

0
source

All Articles