PHP:如何将变量添加到函数名称?

Aar*_*ron 4 php variables function

我有一个回调课.我将一个字符串传递给类,并使用该字符串作为回调函数调用回调.它有点像这样:

$obj->runafter( 'do_this' );

function do_this( $args ) {
    echo 'done';
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是在循环中运行它,以便函数不会被多次写入我想在函数名称中添加一个变量.我想做的是这样的:

for( $i=0;$i<=3;$i++ ) :
    $obj->runafter( 'do_this_' . $i );

    function do_this_{$i}( $args ) {
        echo 'done';
    }
endfor;
Run Code Online (Sandbox Code Playgroud)

关于如何在PHP中完成此任务的任何想法?

jsz*_*ody 6

我会直接将函数作为闭包传递:

for($i=0; $i<=3; $i++) {
    $obj->runafter(function($args) use($i) {
        echo "$i is done";
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意如何use($i)在回调中使用此局部变量(如果需要).

这是一个工作示例:https://3v4l.org/QV66p

有关callables和closures的更多信息:

http://php.net/manual/en/language.types.callable.php