0

In Java it's possible to write some concise functional code by using method references, for example:

class Foo {
    public void method1(List<String> foo) {
        foo.stream().map(this::method2);
    }

    private String method2(String s) {
        return s.toLowerCase() + " bar";
    }
}

Is there a way to do something similar in PHP more concise than:

class Foo {
  public function method1(array $foo) {
    array_map(
        function ($s) {
          return $this->method2($s);
        },
        $foo
    );
  }

  private function method2(string $s) {
    return strtolower($s) . "bar";
  }
}
Chico Sokol
  • 1,254
  • 3
  • 16
  • 24

1 Answers1

0

You can use:

array_map([$this, 'method2'], $foo);
Matt
  • 1,073
  • 1
  • 8
  • 14
  • No, non-public methods work just fine as well. – deceze Nov 27 '20 at 14:44
  • Right you are, removed that bit. Think I misremembered because it has to be `public` when used with Laravel's collections, e.g. `Collection::map` – Matt Nov 27 '20 at 14:45