1

I tried looking everywhere for this, or perhaps it just cannot be done?

So say I want to have a function that is used to create other functions which have a new function name based on a passed in argument, is this even possible?

I keep getting function undefined. Beyond the currying ability, can you name the nested function with a parameter and return the nested function to be called later (by the name you gave it in the parameter)?

function maker_of_functions($secFuncName, $foo) { 
    $secFuncName = function($bar) { 
        $fooBar = $foo + $bar;
    }
    return $secFuncName();
}

The later in the code call:

maker_of_functions('adder', 3);
echo adder(5);
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Secular12
  • 53
  • 4

1 Answers1

2

Using parent function parameters

To create a new function which uses the parent function params, you can use a closure:

function maker_of_functions($foo) { 
    // notice the "use" keyword below
    return function($bar) use ($foo) { 
        return $foo + $bar;
    };
}

and then use it:

$adder = maker_of_functions(3);
echo $adder(5);

Naming the function

A closure is an anonymous function. It does not have a name. It exist as (I think) a reference to a function only, which is contained in a variable. If you want a dynamically named variable, you can:

$name = "myNewNamedFunction";
$$name = maker_of_functions(3);

echo $myNewNamedFunction(6);

Additional information

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129