入れ子の無名関数を呼びたかった
PHPよく分かってない人が書くと簡単な事でもたくさん時間を食うというお話。
結論としてはcall_user_funcを使えとかそれで終わる。
PHP: call_user_func - Manual
# php -v PHP 5.6.2 (cli) (built: Oct 26 2014 20:39:23) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans
- call.php
<?php $myFunc = function() { return function() { return "Hoge"; }; }; echo $myFunc();
こんなのを普通に呼ぶと怒られる。
まぁ返ってきているものを考えれば何出力すりゃいいんだと言われても仕方がない。
# php -f call.php PHP Catchable fatal error: Object of class Closure could not be converted to string in call.php on line 9 PHP Stack trace: PHP 1. {main}() call.php:0 Catchable fatal error: Object of class Closure could not be converted to string in call.php on line 9
こんな書き方するとシンタックスエラーを吐く。
echo $myFunc()->();
# php -f call.php PHP Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in call.php on line 9 Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in call.php on line 9
そこでcall_user_funcですよ。
<?php $myFunc = function() { return function() { return "Hoge"; }; }; echo call_user_func($myFunc());
# php -f call.php
Hoge%
普通は一旦変数に入れてほげもげするのかな?
<?php $myFunc = function() { return function() { return "Hoge"; }; }; $inner = $myFunc(); echo $inner();
# php -f call.php
Hoge%