Arnaud
Arnaud

Reputation: 266

PHP: create an array of functions with a for loop

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:

Upvotes: 0

Views: 88

Answers (1)

Daniel Cheung
Daniel Cheung

Reputation: 4819

<?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.

Upvotes: 2

Related Questions