4

I have a class with a callback. I pass a string to the class and the callback gets called with that string as the callback function. It works a little like this:

$obj->runafter( 'do_this' );

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

What I am looking to do is run this inside of a loop and so that the function doesn't get written multiple times I want to add a variable to the function name. What I want to do is 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 accomplish this in PHP?

0

3 Answers 3

6

I would pass the function in 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) to make this local variable available in your callback if needed.

Here is a working example: https://3v4l.org/QV66p

More info on callables and closures:

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

Sign up to request clarification or add additional context in comments.

7 Comments

Appreciated, that's actually madness x) Nice one!
@KyleE4K just updated with a working example link as well
I wonder if this is possible with C# (more strongly typed languages) - research time haha
@KyleE4K of course it is possible. In C# you can use Delegate
Worked perfectly! Thanks!
|
2

You can assign function to variable and create closure also you can pass variable outside the scope of anonymous function via use keyword

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

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

Useful links:

1 Comment

Upvoted for showing how you can define the function as a closure first. Note you need a semi-colon at the end of the function definition, and you'll get Notice: Undefined variable: i. If notices are turned on.
0

According to your question, you should define your function before the loop. Then you don't have to worry about it being redefined on each loop iteration.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.