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 therefore 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With