What is the closure of a function?
A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables. For example, the adder function returns a closure. Each closure is bound to its own sum variable. Ref
The below code in PHP will throw Error:
$var1 = "test";
$var1 = static function($num) use ($var1) {
if ($num < 1) return 1;
return $var1($num - 1);
};
$var1(5);
echo "ok";
The Solution:
To pass $var1 by reference, so that it will point to last definition of $var1 which is closure function instead of string.
$var1 = "test";
$var1 = static function($num) use (&$var1) {
if ($num < 1) return 1;
return $var1($num - 1);
};
$var1(5);
echo "ok";