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?
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With