I'm trying to write some nested PHP anonymus functions, the structure is the one that 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');
The output is Fatal error: Function name must be a string in this line:
$text = $function_A($code);
This message does not say anything to me :(
The thing here is that your $function_A
is not defined in the global scope, but in the scope of $abc
. If you want you can try using use
in order to pass your $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);
};
In PHP, to pass variables other than $this
and superglobals into an anonymous closure you have to 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's a working example: http://3v4l.org/u1CtZ
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