Anonymous Nested Functions

I am trying to write some nested functions of anonymous PHP, the structure is the one you see below, and my question is: how can I make it work without errors?

$abc = function($code){ $function_A = function($code){ return $code; }; $function_B = function($code){ global $function_A; $text = $function_A($code); return $text; }; $function_B($code); }; echo $abc('abc'); 

Exit Fatal error: function name must be a string in this line:

 $text = $function_A($code); 

This post doesn't tell me anything :(

+6
source share
2 answers

The fact is that your $function_A not defined in the global scope, but in the scope of $abc . If you want, you can try using use to pass $function_A to the scope of your $function_B :

 $abc = function($code){ $function_A = function($code){ return $code; }; $function_B = function($code) use ($function_A){ $text = $function_A($code); return $text; }; $function_B($code); }; 
+10
source

In PHP, to pass variables other than $this and superglobal to anonymous closure, you must use the use statement.

 <?php $abc = function($code){ $function_A = function($code){ return "Code: {$code}"; }; $function_B = function($code) use ($function_A) { $text = $function_A($code); return $text; }; return $function_B($code); }; echo $abc('abc'); 

Here is a working example: http://3v4l.org/u1CtZ

+2
source

Source: https://habr.com/ru/post/986178/


All Articles