0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】無名関数と __invoke() をわかりやすく解説

0
Posted at

まず結論

機能 何をする?
無名関数 名前のない関数
__invoke() オブジェクトを関数のように呼び出せるようにする魔法メソッド

① 無名関数とは?

普通の関数

これは「greet」という名前がある関数。

function greet($name) {
    return "Hello " . $name;
}

無名関数(匿名関数)

・名前がない
・変数に入れて使う


```php
$greet = function ($name) {
    return "Hello " . $name;
};

echo $greet("Taro");

② __invoke() とは?

魔法メソッドの1つ

このメソッドを持つクラスは
オブジェクトを関数のように呼べる

public function __invoke() {}

普通のクラス

class Greeting {
    public function say($name) {
        return "Hello " . $name;
    }
}

$g = new Greeting();
echo $g->say("Taro");

__invoke() を使うと

class Greeting {
    public function __invoke($name) {
        return "Hello " . $name;
    }
}

$g = new Greeting();

echo $g("Taro"); // ← 関数みたいに呼べる!

③無名関数 vs __invoke()

無名関数 __invoke
書き方 function() {} class + __invoke
再利用 しにくい しやすい
テスト しにくい できる
可読性 短い処理向き ロジック向き

④使い分け基準

無名関数

・その場だけ使う
・短い処理
・一度きり

例:
・collectionのmap
・簡単なバリデーション

__invoke

・再利用したい
・テストしたい
・1クラス1責務にしたい
・依存注入したい

例:
・Actionクラス
・Service単発処理
・単一責務クラス

まとめ

■ 無名関数
→ 名前のない関数。短い処理向き。

■ __invoke()
→ オブジェクトを関数のように呼べる。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?