2012-06-13 44 views
4

我想在對象數組上使用array_filter,並使用foo-class的公共方法作爲回調。我不知道該怎麼做。PHP array_filter對象

我得到這個結果:Fatal error: Using $this when not in object context我猜可能是因爲它以靜態方式調用bar方法,但是如何正確地將對象傳遞給array_filter回調方法?

function foobar_filter($obj) { 
    return $obj->bar(); 
} 

class foo { 
    private $value; 
    public function __construct($value) { 
     $this->value = $value; 
    } 
    public function bar() { 
     // checking if $this is set to avoid "using this when not in object yadayada"-message 
     if ($this) return ($this->value > 10); 
     else return false; 
    } 
} 

$arr = array(new foo(12), new foo(42), new foo(4)); 
var_dump($arr); 

// Here is the workaround that makes it work, but I'd like to use the objects' method directly. This is the result that I am expecting to get from $arr3 as well 
$arr2 = array_filter($arr, "foobar_filter"); 
var_dump($arr2); 

// I would like this to work, somehow... 
$arr3 = array_filter($arr, array(foo, "bar")); 
var_dump($arr3); 

所以我希望得到的結果是與值12類foo的兩個對象和42

爲了您的信息的數組,我使用PHP 5.2.6,但我會很高興,如果任何PHP版本都可以。

回答

1

的問題是bar方法不是靜態的,並且需要在每個對象上被調用。您的foobar_filter方法是要走的路。沒有其他辦法,因爲您需要撥打bar每個對象(因此使array_filter每次調用一個不同的函數),您不能靜態調用它。

+0

啊!我的問題是,我認爲'bar'只是在不同的對象上具有相同的功能。我沒有把它看作每個物體的不同功能。 +1並被接受爲答案! –

1

可以在array_filter方法使用的封閉(> = PHP 5.3)這樣

$arrX = array_filter($arr, function($element) { 
    return $element->bar(); 
}); 
var_dump($arrX) 
+1

這基本上是一樣的'foobar_filter'的解決方案,只是一個匿名功能。 –

1

我想你可以靜態調用它是這樣的:

class foo { 
    private $value; 
    public function __construct($value) { 
     $this->value = $value; 
    } 
    public static function bar($a) {   
     if ($a) return ($a->value > 10); 
     else return false; 
    } 
} 

$arr = array(new foo(12), new foo(42), new foo(4)); 

$arr3 = array_filter($arr, array('foo', "bar")); 
var_dump($arr3); 
-1

其實你可以這樣來做

array_filter($arr, [$this, 'bar'])