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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With