closure - PHP函數回調參數如何在回呼函數內使用外部參數

來源:互聯網
上載者:User
直接代碼,使用情境:
現在的代碼:

$gifts = $this->get_list();$gifts = array_filter($gifts,function($v) use ($customer_id){    return call_user_func(array($this,'gift_selector'),$v,$customer_id);});

如果:

$gifts = $this->get_list();$gifts = array_filter($gifts,($this,'gift_selector'));

$gift是可以作為預設參數傳入$this->gift_selector(),但是 外部變數 $customer_id 怎麼傳入呢?

當然,closure的時候可以使用 use ($customer_id) 這個是知道的,不過在這裡想把回呼函數拿出來寫,因為寫成closure太長了。

回複內容:

直接代碼,使用情境:
現在的代碼:

$gifts = $this->get_list();$gifts = array_filter($gifts,function($v) use ($customer_id){    return call_user_func(array($this,'gift_selector'),$v,$customer_id);});

如果:

$gifts = $this->get_list();$gifts = array_filter($gifts,($this,'gift_selector'));

$gift是可以作為預設參數傳入$this->gift_selector(),但是 外部變數 $customer_id 怎麼傳入呢?

當然,closure的時候可以使用 use ($customer_id) 這個是知道的,不過在這裡想把回呼函數拿出來寫,因為寫成closure太長了。

phpclass Demo{    private $customer_id = 0;    public function doit()    {        $gifts = array('1', '2', '3');        $this->customer_id = 3;        $gifts = array_filter($gifts, array($this,'gift_selector'));        return $gifts;    }    private function gift_selector($v)    {        return $v==$this->customer_id ? true : false;    }}$obj    = new Demo();$gifts  = $obj->doit();var_dump($gifts);/*array (size=1)  2 => string '3' (length=1)*/

蟹妖

寫callback硬要傳非參數的值可以通過 @宋小北 那樣的類成員等方式實現,但我個人覺得這類似全域變數傳遞狀態,屬於不好的code smell

我的建議是可以考慮給get_list增加按回調過濾的能力

phpfunction get_list($filter = null) {  $gifts = [];//原本的邏輯..  if(is_callable($filter)) {    $gifts = array_filter($gifts,function($gift) use ($customer_id) {      return call_user_func($filter, $gift, $customer_id);    });  }  return $gifts;}

於是就有

php$this->get_list([$this,'gift_selector']);

了,gift_selector能夠收到$gift, $customer_id作為參數

全域變數,session/cookie,引用傳值

edit:
類屬性賦值
$this->customer_id;

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.