【问题标题】:How to use an object method (with $this) as a callback in array_filter?如何使用对象方法(使用 $this)作为 array_filter 中的回调?
【发布时间】:2019-11-07 00:40:59
【问题描述】:

我为 A 类定义了一个公共方法:

class A{
  public function isValid()
  {
    return $this->getValue==1;
  }
}

我想使用类A中定义的方法过滤对象As的数组:

class B{
  //$input is an array of A objects
  public static function getArray($input)
  {
    return array_filter($input, array($this, “isValid”))
  }
}

然而,实际上$thisB 类中无效。如何在array_filter中输入回调函数使其生效?

【问题讨论】:

  • return array_filter($input, array("A", “isValid”)); ??
  • 如果我这样做,isValid 应该是静态函数吗?
  • 如果它总是静态使用而不是作为对象的一部分,那么是的。
  • 知道了,谢谢! @AbraCadaver

标签: php array-filter


【解决方案1】:

使用调用isValid()的匿名函数

return array_filter($input, function($x) { return $x->isValid(); });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多