matlabmann 2014-08-03 22:06
浏览 27
已采纳

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

This question already has an answer here:

when calling array_filter with a php function you just should do

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

but how do i pass a class method? (static or non-static) for example

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);}
}

i need because i will reuse my filter function in other places in the class, i tried using anonymous functions in static variables but i get error

</div>
  • 写回答

1条回答 默认 最新

  • dongzhi9906 2014-08-03 22:13
    关注

    This should work for the instance method version:

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

    See http://php.net/manual/en/language.types.callable.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?