How can I send a parameter to a compare function in PHP?
To begin, I'm working entirely in PHP using the Yii framework, although Yii ultimately has little to do with this question.
I've got a class, and inside of it I have an array called $data. I want to filter out certain elements of the array that don't match up with the parameters I'm sending to the class (I'll put some syntax below to give you a better idea). I am t开发者_如何转开发herefore using array_filter, and it requires one of its inputs to be a comparison function (ie. one that returns true or false for a specific element. Any that cause a 'false' to be returned are removed from the array).
The problem is that because the function entered is entered in quotes, I don't see a way to have the comparison function within the actual class. But when the function is outside of the class, I can't call the instance variable that I need. So what I really need is to be able to call the instance variable outside of the class somehow, to send the instance variable to the function as a parameter, or to somehow keep the comparison function within the class.
Any ideas on this? The class I mentioned is a widget in Yii. Below is the call to that widget (not that important). The relevant parameter is 'params'.
$this->widget('application.widgets.CListViewParam', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'params'=>array('receiverId'=>Yii::app()->user->userId),
));
There is an instance variable within a class in the widget to save the parameter:
public $params = array();
Then there is a call to array_filter and the comparison function:
$data = array_filter($data, "filterData");
The actual comparison function is not important, but below is the skeleton. Remember that it is outside of the class.
function filterData($item) {
// unable to access $this->params inside of this function!
}
If it's outside the class and can't access $this->params
, then why not just put it inside the class:
class MyClass {
public $params;
public function widget() {
// ...
$filtered = array_filter($array, array($this, 'filterData'));
}
private function filterData($item) {
// $this->params is now accessible
}
}
You can use a lambda construct to use any variables you need in a callback. For instance, instead of hardcoding the value 1.5
in this code:
$array = Array(1.0, 2.0, 3.0, 4.0);
function cmp($x) { return $x > 1.5; }
print_r(array_filter($array, cmp));
You can pass it as a variable to a lambda construct:
$array = Array(1.0, 2.0, 3.0, 4.0);
$data = 1.5;
$lambda = function($x) use ($data) { return $x > $data; };
print_r(array_filter($array, $lambda));
If you wish to modify $data
, use use(&$data)
.
$params = $this->params;
$data = array_filter($data, function($item) use ($params){
});
精彩评论