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);
5
  • whoops that was a typo fixed in edit. Commented Aug 2, 2016 at 20:29
  • If you need currying - maybe search for that? Commented Aug 2, 2016 at 20:30
  • 1
    Possible duplicate of Is it possible to curry method calls in PHP? Commented Aug 2, 2016 at 20:31
  • The question is mainly bout can you define (and name) a nested function with the parent function parameter. Commented Aug 2, 2016 at 20:53
  • If I am not wrong, that child function will only exists as long as the parent function is alive and therefore, can only be used from inside the parent function itself? Commented Aug 2, 2016 at 21:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this will do just fine! Works exactly as I would need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.