Code directly. Use Case: current Code: {code ...} if: {code ...} $ gift can be passed in as the default parameter $ this-& amp; gt; gift_selector (), but how can I pass in the external variable $ customer_id? Of course, you can use the use ($ customer... directly code when closure is used. use Cases:
Current 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'));
$gift
Yes can be passed in as the default parameter$this->gift_selector()
But external variables$customer_id
How can this problem be passed in?
Of course,closure
You can useuse ($customer_id)
I know this, but I want to write the callback function here, because it is writtenclosure
It's too long.
Reply content:
Code directly. Use Cases:
Current 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'));
$gift
Yes can be passed in as the default parameter$this->gift_selector()
But external variables$customer_id
How can this problem be passed in?
Of course,closure
You can useuse ($customer_id)
I know this, but I want to write the callback function here, because it is writtenclosure
It's too long.
php
class 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
Writing callback to pass non-parameter values can be achieved through class members like @ song XiaoBei, but I personally think this is similar to the passing status of global variables and is a bad code smell.
My suggestion is to considerget_list
Added the ability to filter by callback.
php
Function get_list ($ filter = null) {$ gifts = []; // The original logic .. 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']);
Yes, gift_selector can receive$gift, $customer_id
As a parameter
Global variables, session/cookie, reference pass value
Edit:
Class Attribute assignment
$ This-> customer_id;