Created
June 2, 2016 09:02
-
-
Save polidog/2315bbc71e1df176a9593b907b9439ca to your computer and use it in GitHub Desktop.
__invoke()が必要場合ってどんなときだろうって考えてみた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* __invoke()を使う意味がわからなかったけど、よく考えたらcallableな引数渡すときに無名関数じゃなくて、オブジェクト | |
* そのものを渡したい時に使えそうだと思った。 | |
*/ | |
class Hoge { | |
public function __invoke(string $output) | |
{ | |
$this->exec($output); | |
} | |
private function exec(string $output) { | |
// インスタンス変数使えるよねここで | |
echo "Hoge::exec: {$output}\n"; | |
} | |
} | |
function runCheck(string $a, callable $fn) { | |
$fn($a); | |
}; | |
$func = function(string $a) { | |
echo "function exec: {$a}\n"; | |
}; | |
$obj = new \Hoge(); | |
runCheck("test1", $obj); | |
runCheck("test2", $func); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
しかしこの方法はタイプヒンティングがcallableならいけるけど、\Closureだとダメか・・・