6

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 :(

BillyBelly
  • 523
  • 3
  • 14
  • 1
    `$function_A` is not defined in global scope. – AbraCadaver Apr 28 '15 at 19:31
  • 1
    `$function_A` gets defined in the local variable scope of the outer function, not as global. See also [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/q/16959576) – mario Apr 28 '15 at 19:31

2 Answers2

10

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);

};
taxicala
  • 21,408
  • 7
  • 37
  • 66
2

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

Korvin Szanto
  • 4,531
  • 4
  • 19
  • 49