将params传递给内部函数


Passing params to inner function

为什么$poll_idparam在array_map的回调中为NULL(未定义)?下面的代码是有效的,但我不得不使用特殊的private$id类成员来克服它…

class Polls_model extends CI_Model
{
    private $id;
    // ...
    public function add_poll_answers($poll_id, $answers)
    {
        $this->id = $poll_id;
        if (count($answers) > 0)
        {
            $this->db->insert_batch('poll_answers', 
                array_map(
                    function ($a)
                    {
                        log($poll_id); // NULL, why?
                        log($this->id); // correct value
                        return ['name' => $a,'poll_id' => $this->id];
                    }, $answers));
        }
    }
}

变量$poll_id为null,因为其作用域在函数中是本地的。您可以使用php闭包:

function ($a) use ($poll_id)
{
    log($poll_id); // NULL, why?
    log($this->id); // correct value
    return ['name' => $a,'poll_id' => $this->id];
}, $answers));

http://php.net/manual/de/functions.anonymous.php