سؤال

I'm trying to figure out how to use an external variable with my closure

function times2(Array $arr, Closure $callback) {
  foreach ($arr as $n) {
    $callback($n * 2);
  }
}

$foo = array(1,2,3);
$ret = array();

times2($foo, function($n) use($ret) {
  printf("should be adding %d to the array\n", $n);
  array_push($ret, $n);
});

print_r($ret);

Output

should be adding 2 to the array
should be adding 4 to the array
should be adding 6 to the array
Array
(
)

I'm hoping for

should be adding 2 to the array
should be adding 4 to the array
should be adding 6 to the array
Array
(
  [0] => 2,
  [1] => 4,
  [2] => 6
)

But my $ret array is empty!


PS I know this could be done with array_map or array_walk. I'm just trying to figure out how to do it with the Closure.

هل كانت مفيدة؟

المحلول

Well you need to reference $ret instead of copying it. Simply prepend & before the variable name in the anonymous function.

times2($foo, function($n) use(&$ret) {
  printf("should be adding %d to the array\n", $n);
  array_push($ret, $n);
});

نصائح أخرى

Sorry for giving the wrong answer (kind of new here). I know you already selected a correct answer, but I figure I'd correct my mistake anyways. I tested the code below using globals and it works as you request. Thanks for giving me your feedback guys.

function times2(Array $arr, Closure $callback) {

  foreach ($arr as $n) {
    $callback($n * 2);
  }
}

$foo = array(1,2,3);
$ret = array();

times2($foo, function($n) use($ret) {

  global $ret;
  $ret[] = $n;
  echo "should be adding $n to the array</ br>";

});

print_r($ret);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top