Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested anonymus functions

Tags:

php

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

like image 659
BillyBelly Avatar asked Apr 28 '15 19:04

BillyBelly


2 Answers

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

};
like image 199
taxicala Avatar answered Oct 23 '22 22:10

taxicala


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

like image 27
Korvin Szanto Avatar answered Oct 23 '22 20:10

Korvin Szanto