【问题标题】:Array_filter in the context of an object, with private callback对象上下文中的 Array_filter,带有私有回调
【发布时间】:2012-01-04 14:05:09
【问题描述】:

我想过滤一个数组,使用 array_filter 函数。它暗示在水下使用 call_user_func,但没有提及如何在类/对象的上下文中使用。

一些伪代码来解释我的目标:

class RelatedSearchBlock {
  //...
  private function get_filtered_docs() {
    return array_filter($this->get_docs(), 'filter_item');
  }

  private filter_item() {
    return ($doc->somevalue == 123)
  }
}

我需要将 'filter_item' 更改为 array($this, 'filter_item') 吗?我想要的有可能吗?

【问题讨论】:

    标签: php callback array-filter


    【解决方案1】:

    是的:

    return array_filter($this->get_docs(), array($this, 'filter_item'));
    

    请参阅documentation for the callback type

    【讨论】:

    • 好消息!如果您使用的是静态方法,则必须使用过滤器函数传入类名。为此,您可以将array($this, 'filter_item') 替换为array(__CLASS__, 'filter_item')
    • 是在调用array_filter()的对象上调用filter_item()方法,还是在$this->get_docs()中的每个对象上调用filter_item()方法?
    • @Arild 从本质上讲,$this->filter_item($doc) 将为从get_docs() 返回的每个项目调用。
    • 我今天读到的只是 deceze php 答案,感谢上帝,你在这个网站上,认真的..
    猜你喜欢
    • 2014-09-21
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多