Variable Before Calling an Anonymous Function in PHP
Let's consider the following code:
<?php
$pow = 2;
$func = function($num) use ($pow)
{
return $num ** $pow;
};
echo $func(4);
?>
The code above works,
because the variable $pow
is written before the function declaration.
However, if we place the variable declaration
before the function call,
it will stop working:
<?php
$func = function($num) use ($pow)
{
return $num ** $pow;
};
$pow = 2;
echo $func(4);
?>
The problem can be fixed by passing the variable by reference:
<?php
$func = function($num) use (&$pow)
{
return $num ** $pow;
};
$pow = 2;
echo $func(4);
?>
Fix the code so that it works as intended:
<?php
$func = function() use ($num1, $num2)
{
return $num1 + $num2;
};
$num1 = 2;
$num2 = 3;
echo $func();
?>