2015-11-02 113 views
0

为什么$ poll_id在array_map的回调函数中param为NULL(undefined)?下面的代码工作,但我不得不使用专门的私人的$ 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)); 
     } 
    } 
} 
+1

因为你指定'$ poll_id'到'$这个 - > id'代码中的'$这个 - > ID = $ poll_id;' – Saty

+0

实际上斜面明白你在做什么,即使 –

回答

4

变量$ 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

+0

明白了。谢谢! – Sphinx