PHP: How to add a variable to a function name?

I have a class with a callback. I pass the string to the class and the callback is called with that string as a callback function. This is a bit like this:

$obj->runafter( 'do_this' );

function do_this( $args ) {
    echo 'done';
}

What I want to do is run this inside the loop and so that the function is not written several times. I want to add a variable to the function name. I want to do something like this:

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

    function do_this_{$i}( $args ) {
        echo 'done';
    }
endfor;

Any ideas on how I can do this in PHP?

+4
source share
3 answers

I would pass the function directly as a closure:

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

Note how you can use($i)make this local variable available in your callback, if necessary.

: https://3v4l.org/QV66p

:

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

+6

,

$callback = function($args) use($i) {
    echo "$i is done";
};

for ($i = 0; $i <= 3; $i++) {
    $arg = "some argument";
    $obj->runafter($callback($arg));
}

:

+2

According to your question, you should define your function before the loop. Then you do not need to worry about being redefined at each iteration of the loop.

function do_this( $args ) {
    echo 'done';
}

for( $i=0;$i<=3;$i++ ) :
    $obj->runafter( 'do_this' );
endfor;
0
source

All Articles