Direct code, usage scenarios:
Now the code:
$gifts = $this->get_list();$gifts = array_filter($gifts,function($v) use ($customer_id){ return call_user_func(array($this,'gift_selector'),$v,$customer_id);});
If:
$gifts = $this->get_list();$gifts = array_filter($gifts,($this,'gift_selector'));
$giftIt is possible to pass in as a default parameter $this->gift_selector() , but how is an external variable $customer_id passed in?
Of course, closure you can use use ($customer_id) this when you know, but here you want to write the callback function, because it is closure too long written.
Reply content:
Direct code, usage scenarios:
Now the code:
$gifts = $this->get_list();$gifts = array_filter($gifts,function($v) use ($customer_id){ return call_user_func(array($this,'gift_selector'),$v,$customer_id);});
If:
$gifts = $this->get_list();$gifts = array_filter($gifts,($this,'gift_selector'));
$giftIt is possible to pass in as a default parameter $this->gift_selector() , but how is an external variable $customer_id passed in?
Of course, closure you can use use ($customer_id) this when you know, but here you want to write the callback function, because it is closure too long written.
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)*/
Crab Demon
Write callback hard to pass the value of the non-parameter can be achieved by the class members such as song Xiao Bei, but I personally think this is similar to the global variable delivery state, belongs to the bad code smell
My advice is to consider get_list adding the ability to filter by callback
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;}
So there is
php$this->get_list([$this,'gift_selector']);
, Gift_selector was able to receive the $gift, $customer_id parameters as
Global variables, Session/cookie, reference pass-through values
Edit
Class Property Assignment Value
$this->customer_id;