(php)如何在array_filter中将类方法作为回调传递?

时间:2014-08-03 22:06:34

标签: php function oop

使用php函数调用array_filter时,你应该这样做

function myFunc($e) {
    return something($e);
}
array_filter($myArray,"myFunc");

但我如何传递类方法? (静态或非静态) 例如

class A {
    public function foo() {
        //code
        $a = array_filter($array,"self::myFilter");
        //or if myFilter is an instance method
        $a = array_filter($array,"this->myFilter");
    }
    public (static)? function myFilter($e) {return something($e);}
}

我需要因为我会在类中的其他地方重用我的过滤器函数,我尝试在静态变量中使用匿名函数但是我得到错误

1 个答案:

答案 0 :(得分:5)

这适用于实例方法版本:

class A {
    public function foo() {
        $a = array_filter($array, array($this, "myFilter"));
    }
    public function myFilter($e) {return something($e);}
}

请参阅http://php.net/manual/en/language.types.callable.php