PHP Undefined variable in a closure

2020-03-16 02:51发布

The following snippet returns a bunch of input fields but I'm unable to set their values because $data is undefined (it being inside a closure).

$row = array_map(function($n) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));

I know global variables are not cool. What's the best way to get around this?

标签: php
1条回答
forever°为你锁心
2楼-- · 2020-03-16 03:14

Inheriting variables from the parent scope

$row = array_map(function($n) use ($data) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));
查看更多
登录 后发表回答