Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional programming - call function with all parameters

I'm actually experimenting the functional programming in php. I would like to have some precisions about some function calls.

as an example:

function addition($num1){
    return function ($num2) use ($num1){
        return $num1+$num2;
    }
}
$add_2_to = addition(2);
echo $add_2_to(3);
echo $add_2_to(4);

Is there a way to call the addition function with all the parameters? I tried in this way with no chances:

echo addition(2)(3);
like image 739
Arnaud Ncy Avatar asked Sep 04 '15 16:09

Arnaud Ncy


1 Answers

You are pretty close. PHP doesn't have lexical scope so the variable $num1 is not available within the returned function... for that you have to explicitly import it using use

function addition($num1){
    return function ($num2) use ($num1){
        return $num1*$num2;
    };
}
$add_2_to = addition(2);
echo $add_2_to(3);
echo $add_2_to(4);

The syntax you proposed echo addition(2)(3); currently will not work but when php 7 arrives it will. For current versions of php you can use call_user_func to do what you want.

echo call_user_func(addition(2), 3);
like image 158
Orangepill Avatar answered Oct 03 '22 15:10

Orangepill