我试图在一个对象数组上使用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版本都可以实现,我将非常高兴。
foobar_filter
解决方案相同,只是使用了匿名函数。 - gen_Eric