What is the closure of a function?
![](https://blog.khaledalam.net/wp-content/uploads/2023/08/Closure-JS.png)
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:
![](https://blog.khaledalam.net/wp-content/uploads/2023/08/Screenshot-2023-08-31-at-3.37.36-PM-1024x291.png)
$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";
![](https://blog.khaledalam.net/wp-content/uploads/2023/08/Screenshot-2023-08-31-at-3.37.42-PM-1024x277.png)