Search code examples
phparray-filter

How to use an object method (with $this) as a callback in array_filter?


I have a public method defined for class A:

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

I want to filter an array of object As using the method defined in class A:

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

However, actually $this is not valid in class B. How should I input the callback function in the array_filter to make it work?


Solution

  • Use an anonymous function that calls isValid()

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