Functional programming - call function with all parameters

I am actually experimenting with functional php programming. I would like to have some recommendations regarding 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 add function with all parameters? I tried this way with no chance:

 echo addition(2)(3); 
+7
php parameters functional-programming
source share
1 answer

You are pretty close. PHP has no lexical scope, so the variable $ num1 is not available in the returned function ... for this you need 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 suggested is echo addition(2)(3); will not work at present, but when php 7 arrives, it will. For current php versions, you can use call_user_func to accomplish what you want.

 echo call_user_func(addition(2), 3); 
+7
source share

All Articles