2014-02-16

【PHP】JavaScript風の無名関数呼び出しをする方法

js-function-call.jpg

[ PR ]


PHPでも無名関数が使えるようになった

PHP5.3から、PHPでも無名関数が使えるようになりました。

$myfunc = function(){ 
    echo "hello, anonymous-function!";
 };

$myfunc();

// hello, anonymous-function!

JavaScriptでは無名関数が大活躍

無名関数といえばJavaScriptですよね。JQueryで大活躍しています。

JQuery(functino($){
    $('#test').click(function(){
        $(this).css('background', '#ff0000');
    });
});

JavaScriptにはこういう書き方が多いですね。

(function(str){
    console.log('hello, '+ str);
})('world');

ということはPHPでも同じことができるのでは?と思ってきますね。

試しにやってみましょう。

(function($str){
    echo "hello, $str";
})('world');

// Parse error: parse error in php shell code on line 1

あれれ、エラーになっちゃいました。

PHPでは call_user_func()

実は以下のようにすると正しく動きます。

call_user_func(function($str){
    echo "hello, $str";
}, 'world');

// hello, world

PHP 5.3 以前では次のようにします。

function say($str){
    echo "hello, $str";
}

say('world');
// hello, world

call_user_func('say', 'world');
// hello, world
プログラミングの基礎固め (日経BPパソコンベストムック)
日経ソフトウエア
日経BP社 (2014-02-06)
売り上げランキング: 141,089

コメントはTwitterアカウントにお願いします。

RECENT POSTS


[ PR ]

.