8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPのコールバック色々

Last updated at Posted at 2021-06-30

無名関数

オブジェクトのメソッドをコールバックとして使いたい時、無名関数を使って次のように書くことが多いです。

$service = new Service();

array_map(function($item) use ($service) {
    return $service->func($item);
}, $array);

アロー関数

php7.4からはアロー関数という構文が追加され、もう少し楽に書くことができます。
アロー関数は親スコープの変数を自動でバインドするので、無名関数と違ってuseを使う必要がありません。

$service = new Service();

array_map(fn ($item) => $service->func($item), $array);

配列

さらに、PHPのならではの書き方としてこのような書き方もできます。0番目の要素にオブジェクト、1番目の要素に関数名を入れた配列は、PHPではcallableとして扱われ、関数として呼び出すことができるのです。

$service = new Service();

array_map([$service, 'func'], $array);
is_callable([$service, 'func']); // true
[$service, 'func']($param); // 呼び出せる

クラスの静的関数を呼び出すだけなら、インスタンス化すら必要ありません。

array_map([Service::class, 'func'], $array);
array_map('NAME\SPACE\Service::func', $array);

配列を使う方法は他の言語ではあまり見ないため、これだからPHPはクソと言われかねません使用する際はチームメンバーに確認を取るなど、用法容量を守って使いましょう。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?