Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 688
Aaron Avatar asked Feb 07 '23 11:02

Aaron


2 Answers

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

like image 111
jszobody Avatar answered Feb 10 '23 01:02

jszobody


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:

  • http://php.net/manual/en/functions.anonymous.php
  • http://php.net/manual/en/class.closure.php
like image 21
Robert Avatar answered Feb 10 '23 00:02

Robert