Skip to content

Instantly share code, notes, and snippets.

@polidog
Created June 2, 2016 09:02
Show Gist options
  • Save polidog/2315bbc71e1df176a9593b907b9439ca to your computer and use it in GitHub Desktop.
Save polidog/2315bbc71e1df176a9593b907b9439ca to your computer and use it in GitHub Desktop.
__invoke()が必要場合ってどんなときだろうって考えてみた
<?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);
@polidog
Copy link
Author

polidog commented Jun 2, 2016

しかしこの方法はタイプヒンティングがcallableならいけるけど、\Closureだとダメか・・・

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment