对象上的PHP array_filter

Sim*_*erg 5 php object array-filter

我试图array_filter在一个对象数组上使用,并使用foo类的公共方法作为回调.我不知道怎么做.

我得到了这个结果: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);
Run Code Online (Sandbox Code Playgroud)

所以我期望的结果是一个数组,其中包含两个类的对象,foo其值为12和42.

为了您的信息,我使用的是PHP 5.2.6,但如果可以使用任何PHP版本,我会很高兴.

sil*_*lly 6

您可以在 array_filter 方法中使用 Closure (>= PHP 5.3),如下所示

$arrX = array_filter($arr, function($element) {
    return $element->bar();
});
var_dump($arrX)
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 1

问题是该bar方法不是静态的,需要在每个对象上调用。你的foobar_filter方法就是要走的路。没有其他方法,因为您需要调用bar每个对象(因此array_filter每次调用不同的函数),您不能静态调用它。