0

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.
2
  • If is a simple execution, try with php.net/manual/en/functions.arrow.php Commented Jan 24, 2023 at 18:02
  • Thanks. From your link it appears the arrow seems to implicitly use the "use" keyword proposed in Daniel Cheung's answer. Commented Jan 24, 2023 at 18:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! This is so simple, I'm glad this keyword exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.