Array_filter in the context of an object, with pri

2020-07-02 11:57发布

问题:

I want to filter an array, using the array_filter function. It hints at using call_user_func under water, but does not mention anything about how to use within the context of a class/object.

Some pseudocode to explain my goal:

class RelatedSearchBlock {
  //...
  private function get_filtered_docs() {
    return array_filter($this->get_docs(), 'filter_item');
  }

  private filter_item() {
    return ($doc->somevalue == 123)
  }
}

Would I need to change 'filter_item' into array($this, 'filter_item') ? Is what I want possible at all?

回答1:

Yes:

return array_filter($this->get_docs(), array($this, 'filter_item'));

See the documentation for the callback type.