I have some code that needs a list of functions. I want to create automatically part of this list. Scope rules in PHP prevent my following approach to the problem from working:
$list=[];
$i=0;
for(;$i<10; $i ) {
$list []= function() {
// code that --depends-- on $i, like:
return $i;
};
}
// example of use of the 7th function in the list:
echo $list[6]();
Outputs (on my test machine I have PHP 8.1.2)
Warning: Undefined variable $i in [...]/test.php on line [...]
Because when the 7th anonymous function in $list is called by the last line, its body refers to $i, which is local to the function body and does not refer to the loop variable $i. If $i were declared global it would not issue a warning but would not do what I want either.
Notes:
- In some posts here, OO programming is mentioned. But I do not know enough about OO programming and PHP to see how.
create_function
is no more available in PHP 8- I know there are simpler code for outputting 6, like
echo 6;
thanks.
CodePudding user response:
<?php
$list=[];
for($i=0;$i<10; $i ) {
$list []= function() use ($i) { // <--
return $i;
};
}
echo $list[6]();
You are missing the capture phrase in PHP: https://www.php.net/manual/en/functions.anonymous.php
Closures may also inherit variables from the parent scope. Any such variables must be passed to the
use
language construct.