2011-11-23 33 views
10

我想過濾一個數組,使用array_filter函數。它暗示在水下使用call_user_func,但沒有提及如何在類/對象的上下文中使用。Array_filter在一個對象的上下文中,與私人回調

一些僞來解釋我的目標:

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

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

我需要改變'filter_item'array($this, 'filter_item')?是我想要的可能嗎?

回答

36

是:

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

documentation for the callback type

+0

偉大的信息!如果您使用的是靜態方法,則必須使用過濾器函數傳入類名稱。要做到這一點,你可以用'array(__ CLASS__,'filter_item')'替換'array($ this,'filter_item')'。 –

+0

對調用array_filter()的對象或$ this-> get_docs()中的每個對象調用filter_item()方法嗎? – Arild

+1

@Arild從本質上講,將爲'get_docs()'返回的每個項目調用'$ this-> filter_item($ doc)'。 – deceze

相關問題