I am new to PHP and currently learning the concept of closure.
For closure using use() I know that I can do the following:
$y = "hello";
$c = function() use ($y) {
return $y;
};
print_r($c()); // prints out 'hello'
echo '<br />';
However, I have problem on doing a function that returns another anonymous function, for example:
$u = function() {
return function () use ($y) {
return $y;
};
};
print_r($u()); // empty closure object...
echo '<br />';
I know that when I modify the above codes to the below one, then the code works perfectly. BUT I do NOT understand the reason why.
$b = function() use ($y) {
return function () use ($y) {
return $y;
};
};
print_r($b()); // output : [y] => hello
echo'<br />';
In a similar way, I have a question on the below code using global, why it does not work:
$k = function() {
return function() {
global $y;
return $y;
};
};
print_r($k()); // prints out 'Closure Object ( )'
echo '<br />';
Please do NOT tell me how to swap the codes to make it work. As I have tried, and I know how to change and make these codes work. Instead, I would like to know why global and use() does NOT work when I call them in the return of another anonymous function.