I know that this question may have been asked before, but I don't quite understand the whole concept of anonymous functions (closures), and how they would apply specifically to my situation. NB: I know it is quite silly to have all these simple functions, but my task requirements say that I should have all these functions :/ .
I have several functions. In the function below, the parameters $action1
and $action2
will be both replaced by functions:
function dothis($num1, $num2, $action1, $action2)
{
$result = $num1 + $num2;
if ($result > 52){
//do $action1 which is a function
} else {
//do $action2 which is another function
}
return $result;
}
The function dothis
will be called in another function called add
. Here is the add
function:
function add($action1,$action2)
{
$answer = dothis(42, 34, $action1, $action2);
echo $answer;
}
$action1
and $action2
in the add
function are essentially the same as the $action1
and $action2
in the dothis
function. Do they need to have different names now even though they are the same things?
Now, the add
function will be called in the main
function, where the parameters $action1
and $action2
, will be replaced by the actual functions that they correspond to:
function main()
{
add($fun1,$fun2);
echo 'Arithmetic complete';
}
This is the code for $fun1
and $fun2
:
$fun1 = function () {
echo 'Wow! The answer is greater than 52.';
};
$fun2 = function () {
echo 'Oh no! The answer is less than 52.';
};
What should I do, and what do I need to change? I really appreciate any help. Thanks in advance!