1

このようなことは可能ですか?文字列を引数として受け入れる関数があるとしましょう。ただし、この文字列を提供するには、データの処理を行う必要があります。そこで、JSのように、クロージャを使用することにしました。

function i_accept_str($str) {
   // do something with str
}

$someOutsideScopeVar = array(1,2,3);
i_accept_str((function() {
    // do stuff with the $someOutsideScopeVar
    $result = implode(',', $someOutsideScopeVar); // this is silly example
    return $result;
})());

i_accept_str()文字列の結果を直接提供できるように呼び出すときのアイデアです...おそらくcall_user_func効果がないことが知られている方法でそれを行うことができますが、代替手段はありますか?

PHP5.3とPHP5.4の両方のソリューションが受け入れられます(上記の必要な動作はテストされており、PHP 5.3では機能しませんが、PHP 5.4では機能する可能性があります...)。

4

1 に答える 1

2

PHP(> = 5.3.0、5.4.6でテスト済み)では、変数を使用call_user_funcして、外部スコープから変数をインポートする必要がありますuse

<?php

function i_accept_str($str) {
   // do something with str
   echo $str;
}

$someOutsideScopeVar = array(1,2,3);
i_accept_str(call_user_func(function() use ($someOutsideScopeVar) {
    // do stuff with the $someOutsideScopeVar
    $result = implode(',', $someOutsideScopeVar); // this is silly example
    return $result;
}));
于 2013-02-26T18:17:09.517 に答える