直接代碼,使用情境:
現在的代碼:
$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;