6

我正在尝试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);

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

供您参考,我使用的是 PHP 5.2.6,但如果可以使用任何 PHP 版本,我会很高兴。

4

5 回答 5

3

您可以像这样在 array_filter 方法中使用 Closure (>= PHP 5.3)

$arrX = array_filter($arr, function($element) {
    return $element->bar();
});
var_dump($arrX)
于 2012-06-13T14:31:49.420 回答
2

我认为您可以像这样静态地调用它:

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);
于 2014-02-06T21:53:10.130 回答
1

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

于 2012-06-13T14:37:34.240 回答
1

如果您使用的是 PHP 7.1+,您可以通过以下方式实现您的目标:

$arr3 = Arr::filterObjects($arr, 'bar');

使用这个具有有用数组函数的类库。

于 2018-09-05T22:22:30.637 回答
-1

其实你可以这样做

array_filter($arr, [$this, 'bar'])
于 2017-01-17T10:16:31.357 回答